Send channel_{announcement,update} msgs on connection, not timer
[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::{PackedLockTime, Sequence, Transaction, TxIn, TxMerkleNode, 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 bitcoin::hashes::Hash;
59 use sync::{Arc, Mutex};
60
61 use ln::functional_test_utils::*;
62 use ln::chan_utils::CommitmentTransaction;
63
64 #[test]
65 fn test_insane_channel_opens() {
66         // Stand up a network of 2 nodes
67         use ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
68         let mut cfg = UserConfig::default();
69         cfg.channel_handshake_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
70         let chanmon_cfgs = create_chanmon_cfgs(2);
71         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
72         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
73         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
74
75         // Instantiate channel parameters where we push the maximum msats given our
76         // funding satoshis
77         let channel_value_sat = 31337; // same as funding satoshis
78         let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat, &cfg);
79         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
80
81         // Have node0 initiate a channel to node1 with aforementioned parameters
82         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
83
84         // Extract the channel open message from node0 to node1
85         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
86
87         // Test helper that asserts we get the correct error string given a mutator
88         // that supposedly makes the channel open message insane
89         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
90                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
91                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
92                 assert_eq!(msg_events.len(), 1);
93                 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
94                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
95                         match action {
96                                 &ErrorAction::SendErrorMessage { .. } => {
97                                         nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
98                                 },
99                                 _ => panic!("unexpected event!"),
100                         }
101                 } else { assert!(false); }
102         };
103
104         use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
105
106         // Test all mutations that would make the channel open message insane
107         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 });
108         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 });
109
110         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
111
112         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 });
113
114         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
115
116         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 });
117
118         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 });
119
120         insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
121
122         insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
123 }
124
125 #[test]
126 fn test_funding_exceeds_no_wumbo_limit() {
127         // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
128         // them.
129         use ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
130         let chanmon_cfgs = create_chanmon_cfgs(2);
131         let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
132         node_cfgs[1].features = InitFeatures::known().clear_wumbo();
133         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
134         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
135
136         match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None) {
137                 Err(APIError::APIMisuseError { err }) => {
138                         assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
139                 },
140                 _ => panic!()
141         }
142 }
143
144 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
145         // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
146         // but only for them. Because some LSPs do it with some level of trust of the clients (for a
147         // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
148         // in normal testing, we test it explicitly here.
149         let chanmon_cfgs = create_chanmon_cfgs(2);
150         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
151         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
152         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
153         let default_config = UserConfig::default();
154
155         // Have node0 initiate a channel to node1 with aforementioned parameters
156         let mut push_amt = 100_000_000;
157         let feerate_per_kw = 253;
158         let opt_anchors = false;
159         push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(opt_anchors) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
160         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
161
162         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();
163         let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
164         if !send_from_initiator {
165                 open_channel_message.channel_reserve_satoshis = 0;
166                 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
167         }
168         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_message);
169
170         // Extract the channel accept message from node1 to node0
171         let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
172         if send_from_initiator {
173                 accept_channel_message.channel_reserve_satoshis = 0;
174                 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
175         }
176         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel_message);
177         {
178                 let mut lock;
179                 let mut chan = get_channel_ref!(if send_from_initiator { &nodes[1] } else { &nodes[0] }, lock, temp_channel_id);
180                 chan.holder_selected_channel_reserve_satoshis = 0;
181                 chan.holder_max_htlc_value_in_flight_msat = 100_000_000;
182         }
183
184         let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
185         let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
186         create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
187
188         // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
189         // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
190         if send_from_initiator {
191                 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
192                         // Note that for outbound channels we have to consider the commitment tx fee and the
193                         // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
194                         // well as an additional HTLC.
195                         - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, opt_anchors));
196         } else {
197                 send_payment(&nodes[1], &[&nodes[0]], push_amt);
198         }
199 }
200
201 #[test]
202 fn test_counterparty_no_reserve() {
203         do_test_counterparty_no_reserve(true);
204         do_test_counterparty_no_reserve(false);
205 }
206
207 #[test]
208 fn test_async_inbound_update_fee() {
209         let chanmon_cfgs = create_chanmon_cfgs(2);
210         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
211         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
212         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
213         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
214
215         // balancing
216         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
217
218         // A                                        B
219         // update_fee                            ->
220         // send (1) commitment_signed            -.
221         //                                       <- update_add_htlc/commitment_signed
222         // send (2) RAA (awaiting remote revoke) -.
223         // (1) commitment_signed is delivered    ->
224         //                                       .- send (3) RAA (awaiting remote revoke)
225         // (2) RAA is delivered                  ->
226         //                                       .- send (4) commitment_signed
227         //                                       <- (3) RAA is delivered
228         // send (5) commitment_signed            -.
229         //                                       <- (4) commitment_signed is delivered
230         // send (6) RAA                          -.
231         // (5) commitment_signed is delivered    ->
232         //                                       <- RAA
233         // (6) RAA is delivered                  ->
234
235         // First nodes[0] generates an update_fee
236         {
237                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
238                 *feerate_lock += 20;
239         }
240         nodes[0].node.timer_tick_occurred();
241         check_added_monitors!(nodes[0], 1);
242
243         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
244         assert_eq!(events_0.len(), 1);
245         let (update_msg, commitment_signed) = match events_0[0] { // (1)
246                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
247                         (update_fee.as_ref(), commitment_signed)
248                 },
249                 _ => panic!("Unexpected event"),
250         };
251
252         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
253
254         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
255         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
256         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
257         check_added_monitors!(nodes[1], 1);
258
259         let payment_event = {
260                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
261                 assert_eq!(events_1.len(), 1);
262                 SendEvent::from_event(events_1.remove(0))
263         };
264         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
265         assert_eq!(payment_event.msgs.len(), 1);
266
267         // ...now when the messages get delivered everyone should be happy
268         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
269         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
270         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
271         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
272         check_added_monitors!(nodes[0], 1);
273
274         // deliver(1), generate (3):
275         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
276         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
277         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
278         check_added_monitors!(nodes[1], 1);
279
280         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
281         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
282         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
283         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
284         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
285         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
286         assert!(bs_update.update_fee.is_none()); // (4)
287         check_added_monitors!(nodes[1], 1);
288
289         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
290         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
291         assert!(as_update.update_add_htlcs.is_empty()); // (5)
292         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
293         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
294         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
295         assert!(as_update.update_fee.is_none()); // (5)
296         check_added_monitors!(nodes[0], 1);
297
298         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
299         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
300         // only (6) so get_event_msg's assert(len == 1) passes
301         check_added_monitors!(nodes[0], 1);
302
303         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
304         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
305         check_added_monitors!(nodes[1], 1);
306
307         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
308         check_added_monitors!(nodes[0], 1);
309
310         let events_2 = nodes[0].node.get_and_clear_pending_events();
311         assert_eq!(events_2.len(), 1);
312         match events_2[0] {
313                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
314                 _ => panic!("Unexpected event"),
315         }
316
317         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
318         check_added_monitors!(nodes[1], 1);
319 }
320
321 #[test]
322 fn test_update_fee_unordered_raa() {
323         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
324         // crash in an earlier version of the update_fee patch)
325         let chanmon_cfgs = create_chanmon_cfgs(2);
326         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
327         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
328         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
329         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
330
331         // balancing
332         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
333
334         // First nodes[0] generates an update_fee
335         {
336                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
337                 *feerate_lock += 20;
338         }
339         nodes[0].node.timer_tick_occurred();
340         check_added_monitors!(nodes[0], 1);
341
342         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
343         assert_eq!(events_0.len(), 1);
344         let update_msg = match events_0[0] { // (1)
345                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
346                         update_fee.as_ref()
347                 },
348                 _ => panic!("Unexpected event"),
349         };
350
351         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
352
353         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
354         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
355         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
356         check_added_monitors!(nodes[1], 1);
357
358         let payment_event = {
359                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
360                 assert_eq!(events_1.len(), 1);
361                 SendEvent::from_event(events_1.remove(0))
362         };
363         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
364         assert_eq!(payment_event.msgs.len(), 1);
365
366         // ...now when the messages get delivered everyone should be happy
367         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
368         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
369         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
370         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
371         check_added_monitors!(nodes[0], 1);
372
373         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
374         check_added_monitors!(nodes[1], 1);
375
376         // We can't continue, sadly, because our (1) now has a bogus signature
377 }
378
379 #[test]
380 fn test_multi_flight_update_fee() {
381         let chanmon_cfgs = create_chanmon_cfgs(2);
382         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
383         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
384         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
385         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
386
387         // A                                        B
388         // update_fee/commitment_signed          ->
389         //                                       .- send (1) RAA and (2) commitment_signed
390         // update_fee (never committed)          ->
391         // (3) update_fee                        ->
392         // We have to manually generate the above update_fee, it is allowed by the protocol but we
393         // don't track which updates correspond to which revoke_and_ack responses so we're in
394         // AwaitingRAA mode and will not generate the update_fee yet.
395         //                                       <- (1) RAA delivered
396         // (3) is generated and send (4) CS      -.
397         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
398         // know the per_commitment_point to use for it.
399         //                                       <- (2) commitment_signed delivered
400         // revoke_and_ack                        ->
401         //                                          B should send no response here
402         // (4) commitment_signed delivered       ->
403         //                                       <- RAA/commitment_signed delivered
404         // revoke_and_ack                        ->
405
406         // First nodes[0] generates an update_fee
407         let initial_feerate;
408         {
409                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
410                 initial_feerate = *feerate_lock;
411                 *feerate_lock = initial_feerate + 20;
412         }
413         nodes[0].node.timer_tick_occurred();
414         check_added_monitors!(nodes[0], 1);
415
416         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
417         assert_eq!(events_0.len(), 1);
418         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
419                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
420                         (update_fee.as_ref().unwrap(), commitment_signed)
421                 },
422                 _ => panic!("Unexpected event"),
423         };
424
425         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
426         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
427         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
428         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
429         check_added_monitors!(nodes[1], 1);
430
431         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
432         // transaction:
433         {
434                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
435                 *feerate_lock = initial_feerate + 40;
436         }
437         nodes[0].node.timer_tick_occurred();
438         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
439         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
440
441         // Create the (3) update_fee message that nodes[0] will generate before it does...
442         let mut update_msg_2 = msgs::UpdateFee {
443                 channel_id: update_msg_1.channel_id.clone(),
444                 feerate_per_kw: (initial_feerate + 30) as u32,
445         };
446
447         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
448
449         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
450         // Deliver (3)
451         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
452
453         // Deliver (1), generating (3) and (4)
454         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
455         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
456         check_added_monitors!(nodes[0], 1);
457         assert!(as_second_update.update_add_htlcs.is_empty());
458         assert!(as_second_update.update_fulfill_htlcs.is_empty());
459         assert!(as_second_update.update_fail_htlcs.is_empty());
460         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
461         // Check that the update_fee newly generated matches what we delivered:
462         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
463         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
464
465         // Deliver (2) commitment_signed
466         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
467         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
468         check_added_monitors!(nodes[0], 1);
469         // No commitment_signed so get_event_msg's assert(len == 1) passes
470
471         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
472         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
473         check_added_monitors!(nodes[1], 1);
474
475         // Delever (4)
476         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
477         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
478         check_added_monitors!(nodes[1], 1);
479
480         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
481         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
482         check_added_monitors!(nodes[0], 1);
483
484         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
485         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
486         // No commitment_signed so get_event_msg's assert(len == 1) passes
487         check_added_monitors!(nodes[0], 1);
488
489         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
490         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
491         check_added_monitors!(nodes[1], 1);
492 }
493
494 fn do_test_sanity_on_in_flight_opens(steps: u8) {
495         // Previously, we had issues deserializing channels when we hadn't connected the first block
496         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
497         // serialization round-trips and simply do steps towards opening a channel and then drop the
498         // Node objects.
499
500         let chanmon_cfgs = create_chanmon_cfgs(2);
501         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
502         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
503         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
504
505         if steps & 0b1000_0000 != 0{
506                 let block = Block {
507                         header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
508                         txdata: vec![],
509                 };
510                 connect_block(&nodes[0], &block);
511                 connect_block(&nodes[1], &block);
512         }
513
514         if steps & 0x0f == 0 { return; }
515         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
516         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
517
518         if steps & 0x0f == 1 { return; }
519         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
520         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
521
522         if steps & 0x0f == 2 { return; }
523         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
524
525         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
526
527         if steps & 0x0f == 3 { return; }
528         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
529         check_added_monitors!(nodes[0], 0);
530         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
531
532         if steps & 0x0f == 4 { return; }
533         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
534         {
535                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
536                 assert_eq!(added_monitors.len(), 1);
537                 assert_eq!(added_monitors[0].0, funding_output);
538                 added_monitors.clear();
539         }
540         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
541
542         if steps & 0x0f == 5 { return; }
543         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
544         {
545                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
546                 assert_eq!(added_monitors.len(), 1);
547                 assert_eq!(added_monitors[0].0, funding_output);
548                 added_monitors.clear();
549         }
550
551         let events_4 = nodes[0].node.get_and_clear_pending_events();
552         assert_eq!(events_4.len(), 0);
553
554         if steps & 0x0f == 6 { return; }
555         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
556
557         if steps & 0x0f == 7 { return; }
558         confirm_transaction_at(&nodes[0], &tx, 2);
559         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
560         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
561 }
562
563 #[test]
564 fn test_sanity_on_in_flight_opens() {
565         do_test_sanity_on_in_flight_opens(0);
566         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
567         do_test_sanity_on_in_flight_opens(1);
568         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
569         do_test_sanity_on_in_flight_opens(2);
570         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
571         do_test_sanity_on_in_flight_opens(3);
572         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
573         do_test_sanity_on_in_flight_opens(4);
574         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
575         do_test_sanity_on_in_flight_opens(5);
576         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
577         do_test_sanity_on_in_flight_opens(6);
578         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
579         do_test_sanity_on_in_flight_opens(7);
580         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
581         do_test_sanity_on_in_flight_opens(8);
582         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
583 }
584
585 #[test]
586 fn test_update_fee_vanilla() {
587         let chanmon_cfgs = create_chanmon_cfgs(2);
588         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
589         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
590         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
591         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
592
593         {
594                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
595                 *feerate_lock += 25;
596         }
597         nodes[0].node.timer_tick_occurred();
598         check_added_monitors!(nodes[0], 1);
599
600         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
601         assert_eq!(events_0.len(), 1);
602         let (update_msg, commitment_signed) = match events_0[0] {
603                         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 } } => {
604                         (update_fee.as_ref(), commitment_signed)
605                 },
606                 _ => panic!("Unexpected event"),
607         };
608         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
609
610         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
611         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
612         check_added_monitors!(nodes[1], 1);
613
614         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
615         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
616         check_added_monitors!(nodes[0], 1);
617
618         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
619         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
620         // No commitment_signed so get_event_msg's assert(len == 1) passes
621         check_added_monitors!(nodes[0], 1);
622
623         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
624         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
625         check_added_monitors!(nodes[1], 1);
626 }
627
628 #[test]
629 fn test_update_fee_that_funder_cannot_afford() {
630         let chanmon_cfgs = create_chanmon_cfgs(2);
631         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
632         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
633         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
634         let channel_value = 5000;
635         let push_sats = 700;
636         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000, InitFeatures::known(), InitFeatures::known());
637         let channel_id = chan.2;
638         let secp_ctx = Secp256k1::new();
639         let default_config = UserConfig::default();
640         let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value, &default_config);
641
642         let opt_anchors = false;
643
644         // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
645         // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
646         // calculate two different feerates here - the expected local limit as well as the expected
647         // remote limit.
648         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;
649         let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
650         {
651                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
652                 *feerate_lock = feerate;
653         }
654         nodes[0].node.timer_tick_occurred();
655         check_added_monitors!(nodes[0], 1);
656         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
657
658         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
659
660         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
661
662         // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
663         {
664                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
665
666                 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
667                 assert_eq!(commitment_tx.output.len(), 2);
668                 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
669                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
670                 actual_fee = channel_value - actual_fee;
671                 assert_eq!(total_fee, actual_fee);
672         }
673
674         {
675                 // Increment the feerate by a small constant, accounting for rounding errors
676                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
677                 *feerate_lock += 4;
678         }
679         nodes[0].node.timer_tick_occurred();
680         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
681         check_added_monitors!(nodes[0], 0);
682
683         const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
684
685         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
686         // needed to sign the new commitment tx and (2) sign the new commitment tx.
687         let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
688                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
689                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
690                 let chan_signer = local_chan.get_signer();
691                 let pubkeys = chan_signer.pubkeys();
692                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
693                  pubkeys.funding_pubkey)
694         };
695         let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
696                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
697                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
698                 let chan_signer = remote_chan.get_signer();
699                 let pubkeys = chan_signer.pubkeys();
700                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
701                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
702                  pubkeys.funding_pubkey)
703         };
704
705         // Assemble the set of keys we can use for signatures for our commitment_signed message.
706         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
707                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
708
709         let res = {
710                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
711                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
712                 let local_chan_signer = local_chan.get_signer();
713                 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
714                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
715                         INITIAL_COMMITMENT_NUMBER - 1,
716                         push_sats,
717                         channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
718                         opt_anchors, local_funding, remote_funding,
719                         commit_tx_keys.clone(),
720                         non_buffer_feerate + 4,
721                         &mut htlcs,
722                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
723                 );
724                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
725         };
726
727         let commit_signed_msg = msgs::CommitmentSigned {
728                 channel_id: chan.2,
729                 signature: res.0,
730                 htlc_signatures: res.1
731         };
732
733         let update_fee = msgs::UpdateFee {
734                 channel_id: chan.2,
735                 feerate_per_kw: non_buffer_feerate + 4,
736         };
737
738         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
739
740         //While producing the commitment_signed response after handling a received update_fee request the
741         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
742         //Should produce and error.
743         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
744         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
745         check_added_monitors!(nodes[1], 1);
746         check_closed_broadcast!(nodes[1], true);
747         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
748 }
749
750 #[test]
751 fn test_update_fee_with_fundee_update_add_htlc() {
752         let chanmon_cfgs = create_chanmon_cfgs(2);
753         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
754         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
755         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
756         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
757
758         // balancing
759         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
760
761         {
762                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
763                 *feerate_lock += 20;
764         }
765         nodes[0].node.timer_tick_occurred();
766         check_added_monitors!(nodes[0], 1);
767
768         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
769         assert_eq!(events_0.len(), 1);
770         let (update_msg, commitment_signed) = match events_0[0] {
771                         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 } } => {
772                         (update_fee.as_ref(), commitment_signed)
773                 },
774                 _ => panic!("Unexpected event"),
775         };
776         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
777         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
778         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
779         check_added_monitors!(nodes[1], 1);
780
781         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
782
783         // nothing happens since node[1] is in AwaitingRemoteRevoke
784         nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
785         {
786                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
787                 assert_eq!(added_monitors.len(), 0);
788                 added_monitors.clear();
789         }
790         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
791         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
792         // node[1] has nothing to do
793
794         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
795         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
796         check_added_monitors!(nodes[0], 1);
797
798         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
799         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
800         // No commitment_signed so get_event_msg's assert(len == 1) passes
801         check_added_monitors!(nodes[0], 1);
802         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
803         check_added_monitors!(nodes[1], 1);
804         // AwaitingRemoteRevoke ends here
805
806         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
807         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
808         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
809         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
810         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
811         assert_eq!(commitment_update.update_fee.is_none(), true);
812
813         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
814         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
815         check_added_monitors!(nodes[0], 1);
816         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
817
818         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
819         check_added_monitors!(nodes[1], 1);
820         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
821
822         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
823         check_added_monitors!(nodes[1], 1);
824         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
825         // No commitment_signed so get_event_msg's assert(len == 1) passes
826
827         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
828         check_added_monitors!(nodes[0], 1);
829         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
830
831         expect_pending_htlcs_forwardable!(nodes[0]);
832
833         let events = nodes[0].node.get_and_clear_pending_events();
834         assert_eq!(events.len(), 1);
835         match events[0] {
836                 Event::PaymentReceived { .. } => { },
837                 _ => panic!("Unexpected event"),
838         };
839
840         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
841
842         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
843         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
844         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
845         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
846         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
847 }
848
849 #[test]
850 fn test_update_fee() {
851         let chanmon_cfgs = create_chanmon_cfgs(2);
852         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
853         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
854         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
855         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
856         let channel_id = chan.2;
857
858         // A                                        B
859         // (1) update_fee/commitment_signed      ->
860         //                                       <- (2) revoke_and_ack
861         //                                       .- send (3) commitment_signed
862         // (4) update_fee/commitment_signed      ->
863         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
864         //                                       <- (3) commitment_signed delivered
865         // send (6) revoke_and_ack               -.
866         //                                       <- (5) deliver revoke_and_ack
867         // (6) deliver revoke_and_ack            ->
868         //                                       .- send (7) commitment_signed in response to (4)
869         //                                       <- (7) deliver commitment_signed
870         // revoke_and_ack                        ->
871
872         // Create and deliver (1)...
873         let feerate;
874         {
875                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
876                 feerate = *feerate_lock;
877                 *feerate_lock = feerate + 20;
878         }
879         nodes[0].node.timer_tick_occurred();
880         check_added_monitors!(nodes[0], 1);
881
882         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
883         assert_eq!(events_0.len(), 1);
884         let (update_msg, commitment_signed) = match events_0[0] {
885                         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 } } => {
886                         (update_fee.as_ref(), commitment_signed)
887                 },
888                 _ => panic!("Unexpected event"),
889         };
890         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
891
892         // Generate (2) and (3):
893         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
894         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
895         check_added_monitors!(nodes[1], 1);
896
897         // Deliver (2):
898         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
899         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
900         check_added_monitors!(nodes[0], 1);
901
902         // Create and deliver (4)...
903         {
904                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
905                 *feerate_lock = feerate + 30;
906         }
907         nodes[0].node.timer_tick_occurred();
908         check_added_monitors!(nodes[0], 1);
909         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
910         assert_eq!(events_0.len(), 1);
911         let (update_msg, commitment_signed) = match events_0[0] {
912                         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 } } => {
913                         (update_fee.as_ref(), commitment_signed)
914                 },
915                 _ => panic!("Unexpected event"),
916         };
917
918         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
919         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
920         check_added_monitors!(nodes[1], 1);
921         // ... creating (5)
922         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
923         // No commitment_signed so get_event_msg's assert(len == 1) passes
924
925         // Handle (3), creating (6):
926         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
927         check_added_monitors!(nodes[0], 1);
928         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
929         // No commitment_signed so get_event_msg's assert(len == 1) passes
930
931         // Deliver (5):
932         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
933         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
934         check_added_monitors!(nodes[0], 1);
935
936         // Deliver (6), creating (7):
937         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
938         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
939         assert!(commitment_update.update_add_htlcs.is_empty());
940         assert!(commitment_update.update_fulfill_htlcs.is_empty());
941         assert!(commitment_update.update_fail_htlcs.is_empty());
942         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
943         assert!(commitment_update.update_fee.is_none());
944         check_added_monitors!(nodes[1], 1);
945
946         // Deliver (7)
947         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
948         check_added_monitors!(nodes[0], 1);
949         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
950         // No commitment_signed so get_event_msg's assert(len == 1) passes
951
952         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
953         check_added_monitors!(nodes[1], 1);
954         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
955
956         assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
957         assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
958         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
959         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
960         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
961 }
962
963 #[test]
964 fn fake_network_test() {
965         // Simple test which builds a network of ChannelManagers, connects them to each other, and
966         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
967         let chanmon_cfgs = create_chanmon_cfgs(4);
968         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
969         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
970         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
971
972         // Create some initial channels
973         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
974         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
975         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
976
977         // Rebalance the network a bit by relaying one payment through all the channels...
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         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
982
983         // Send some more payments
984         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
985         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
986         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
987
988         // Test failure packets
989         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
990         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
991
992         // Add a new channel that skips 3
993         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
994
995         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
996         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
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         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1002
1003         // Do some rebalance loop payments, simultaneously
1004         let mut hops = Vec::with_capacity(3);
1005         hops.push(RouteHop {
1006                 pubkey: nodes[2].node.get_our_node_id(),
1007                 node_features: NodeFeatures::empty(),
1008                 short_channel_id: chan_2.0.contents.short_channel_id,
1009                 channel_features: ChannelFeatures::empty(),
1010                 fee_msat: 0,
1011                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1012         });
1013         hops.push(RouteHop {
1014                 pubkey: nodes[3].node.get_our_node_id(),
1015                 node_features: NodeFeatures::empty(),
1016                 short_channel_id: chan_3.0.contents.short_channel_id,
1017                 channel_features: ChannelFeatures::empty(),
1018                 fee_msat: 0,
1019                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1020         });
1021         hops.push(RouteHop {
1022                 pubkey: nodes[1].node.get_our_node_id(),
1023                 node_features: NodeFeatures::known(),
1024                 short_channel_id: chan_4.0.contents.short_channel_id,
1025                 channel_features: ChannelFeatures::known(),
1026                 fee_msat: 1000000,
1027                 cltv_expiry_delta: TEST_FINAL_CLTV,
1028         });
1029         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;
1030         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;
1031         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;
1032
1033         let mut hops = Vec::with_capacity(3);
1034         hops.push(RouteHop {
1035                 pubkey: nodes[3].node.get_our_node_id(),
1036                 node_features: NodeFeatures::empty(),
1037                 short_channel_id: chan_4.0.contents.short_channel_id,
1038                 channel_features: ChannelFeatures::empty(),
1039                 fee_msat: 0,
1040                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1041         });
1042         hops.push(RouteHop {
1043                 pubkey: nodes[2].node.get_our_node_id(),
1044                 node_features: NodeFeatures::empty(),
1045                 short_channel_id: chan_3.0.contents.short_channel_id,
1046                 channel_features: ChannelFeatures::empty(),
1047                 fee_msat: 0,
1048                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1049         });
1050         hops.push(RouteHop {
1051                 pubkey: nodes[1].node.get_our_node_id(),
1052                 node_features: NodeFeatures::known(),
1053                 short_channel_id: chan_2.0.contents.short_channel_id,
1054                 channel_features: ChannelFeatures::known(),
1055                 fee_msat: 1000000,
1056                 cltv_expiry_delta: TEST_FINAL_CLTV,
1057         });
1058         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;
1059         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;
1060         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;
1061
1062         // Claim the rebalances...
1063         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1064         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1065
1066         // Close down the channels...
1067         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1068         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1069         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1070         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1071         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1072         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1073         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1074         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1075         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1076         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1077         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1078         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1079 }
1080
1081 #[test]
1082 fn holding_cell_htlc_counting() {
1083         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1084         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1085         // commitment dance rounds.
1086         let chanmon_cfgs = create_chanmon_cfgs(3);
1087         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1088         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1089         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1090         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1091         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1092
1093         let mut payments = Vec::new();
1094         for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1095                 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1096                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
1097                 payments.push((payment_preimage, payment_hash));
1098         }
1099         check_added_monitors!(nodes[1], 1);
1100
1101         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1102         assert_eq!(events.len(), 1);
1103         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1104         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1105
1106         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1107         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1108         // another HTLC.
1109         let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1110         {
1111                 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)), true, APIError::ChannelUnavailable { ref err },
1112                         assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1113                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1114                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1115         }
1116
1117         // This should also be true if we try to forward a payment.
1118         let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1119         {
1120                 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
1121                 check_added_monitors!(nodes[0], 1);
1122         }
1123
1124         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1125         assert_eq!(events.len(), 1);
1126         let payment_event = SendEvent::from_event(events.pop().unwrap());
1127         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1128
1129         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1130         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1131         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1132         // fails), the second will process the resulting failure and fail the HTLC backward.
1133         expect_pending_htlcs_forwardable!(nodes[1]);
1134         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 }]);
1135         check_added_monitors!(nodes[1], 1);
1136
1137         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1138         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1139         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1140
1141         expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1142
1143         // Now forward all the pending HTLCs and claim them back
1144         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1145         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1146         check_added_monitors!(nodes[2], 1);
1147
1148         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1149         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1150         check_added_monitors!(nodes[1], 1);
1151         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1152
1153         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1154         check_added_monitors!(nodes[1], 1);
1155         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1156
1157         for ref update in as_updates.update_add_htlcs.iter() {
1158                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1159         }
1160         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1161         check_added_monitors!(nodes[2], 1);
1162         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1163         check_added_monitors!(nodes[2], 1);
1164         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1165
1166         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1167         check_added_monitors!(nodes[1], 1);
1168         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1169         check_added_monitors!(nodes[1], 1);
1170         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1171
1172         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1173         check_added_monitors!(nodes[2], 1);
1174
1175         expect_pending_htlcs_forwardable!(nodes[2]);
1176
1177         let events = nodes[2].node.get_and_clear_pending_events();
1178         assert_eq!(events.len(), payments.len());
1179         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1180                 match event {
1181                         &Event::PaymentReceived { ref payment_hash, .. } => {
1182                                 assert_eq!(*payment_hash, *hash);
1183                         },
1184                         _ => panic!("Unexpected event"),
1185                 };
1186         }
1187
1188         for (preimage, _) in payments.drain(..) {
1189                 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1190         }
1191
1192         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1193 }
1194
1195 #[test]
1196 fn duplicate_htlc_test() {
1197         // Test that we accept duplicate payment_hash HTLCs across the network and that
1198         // claiming/failing them are all separate and don't affect each other
1199         let chanmon_cfgs = create_chanmon_cfgs(6);
1200         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1201         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1202         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1203
1204         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1205         create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1206         create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1207         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1208         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1209         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1210
1211         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1212
1213         *nodes[0].network_payment_count.borrow_mut() -= 1;
1214         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1215
1216         *nodes[0].network_payment_count.borrow_mut() -= 1;
1217         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1218
1219         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1220         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1221         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1222 }
1223
1224 #[test]
1225 fn test_duplicate_htlc_different_direction_onchain() {
1226         // Test that ChannelMonitor doesn't generate 2 preimage txn
1227         // when we have 2 HTLCs with same preimage that go across a node
1228         // in opposite directions, even with the same payment secret.
1229         let chanmon_cfgs = create_chanmon_cfgs(2);
1230         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1231         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1232         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1233
1234         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1235
1236         // balancing
1237         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1238
1239         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1240
1241         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1242         let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200).unwrap();
1243         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1244
1245         // Provide preimage to node 0 by claiming payment
1246         nodes[0].node.claim_funds(payment_preimage);
1247         expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1248         check_added_monitors!(nodes[0], 1);
1249
1250         // Broadcast node 1 commitment txn
1251         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1252
1253         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1254         let mut has_both_htlcs = 0; // check htlcs match ones committed
1255         for outp in remote_txn[0].output.iter() {
1256                 if outp.value == 800_000 / 1000 {
1257                         has_both_htlcs += 1;
1258                 } else if outp.value == 900_000 / 1000 {
1259                         has_both_htlcs += 1;
1260                 }
1261         }
1262         assert_eq!(has_both_htlcs, 2);
1263
1264         mine_transaction(&nodes[0], &remote_txn[0]);
1265         check_added_monitors!(nodes[0], 1);
1266         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1267         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1268
1269         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1270         assert_eq!(claim_txn.len(), 8);
1271
1272         check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1273
1274         check_spends!(claim_txn[1], chan_1.3); // Alternative commitment tx
1275         check_spends!(claim_txn[2], claim_txn[1]); // HTLC spend in alternative commitment tx
1276
1277         let bump_tx = if claim_txn[1] == claim_txn[4] {
1278                 assert_eq!(claim_txn[1], claim_txn[4]);
1279                 assert_eq!(claim_txn[2], claim_txn[5]);
1280
1281                 check_spends!(claim_txn[7], claim_txn[1]); // HTLC timeout on alternative commitment tx
1282
1283                 check_spends!(claim_txn[3], remote_txn[0]); // HTLC timeout on broadcasted commitment tx
1284                 &claim_txn[3]
1285         } else {
1286                 assert_eq!(claim_txn[1], claim_txn[3]);
1287                 assert_eq!(claim_txn[2], claim_txn[4]);
1288
1289                 check_spends!(claim_txn[5], claim_txn[1]); // HTLC timeout on alternative commitment tx
1290
1291                 check_spends!(claim_txn[7], remote_txn[0]); // HTLC timeout on broadcasted commitment tx
1292
1293                 &claim_txn[7]
1294         };
1295
1296         assert_eq!(claim_txn[0].input.len(), 1);
1297         assert_eq!(bump_tx.input.len(), 1);
1298         assert_eq!(claim_txn[0].input[0].previous_output, bump_tx.input[0].previous_output);
1299
1300         assert_eq!(claim_txn[0].input.len(), 1);
1301         assert_eq!(claim_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1302         assert_eq!(remote_txn[0].output[claim_txn[0].input[0].previous_output.vout as usize].value, 800);
1303
1304         assert_eq!(claim_txn[6].input.len(), 1);
1305         assert_eq!(claim_txn[6].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1306         check_spends!(claim_txn[6], remote_txn[0]);
1307         assert_eq!(remote_txn[0].output[claim_txn[6].input[0].previous_output.vout as usize].value, 900);
1308
1309         let events = nodes[0].node.get_and_clear_pending_msg_events();
1310         assert_eq!(events.len(), 3);
1311         for e in events {
1312                 match e {
1313                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1314                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1315                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1316                                 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1317                         },
1318                         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, .. } } => {
1319                                 assert!(update_add_htlcs.is_empty());
1320                                 assert!(update_fail_htlcs.is_empty());
1321                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1322                                 assert!(update_fail_malformed_htlcs.is_empty());
1323                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1324                         },
1325                         _ => panic!("Unexpected event"),
1326                 }
1327         }
1328 }
1329
1330 #[test]
1331 fn test_basic_channel_reserve() {
1332         let chanmon_cfgs = create_chanmon_cfgs(2);
1333         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1334         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1335         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1336         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1337
1338         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1339         let channel_reserve = chan_stat.channel_reserve_msat;
1340
1341         // The 2* and +1 are for the fee spike reserve.
1342         let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1, get_opt_anchors!(nodes[0], chan.2));
1343         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1344         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1345         let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).err().unwrap();
1346         match err {
1347                 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1348                         match &fails[0] {
1349                                 &APIError::ChannelUnavailable{ref err} =>
1350                                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1351                                 _ => panic!("Unexpected error variant"),
1352                         }
1353                 },
1354                 _ => panic!("Unexpected error variant"),
1355         }
1356         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1357         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);
1358
1359         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1360 }
1361
1362 #[test]
1363 fn test_fee_spike_violation_fails_htlc() {
1364         let chanmon_cfgs = create_chanmon_cfgs(2);
1365         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1366         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1367         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1368         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1369
1370         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1371         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1372         let secp_ctx = Secp256k1::new();
1373         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1374
1375         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1376
1377         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1378         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1379         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1380         let msg = msgs::UpdateAddHTLC {
1381                 channel_id: chan.2,
1382                 htlc_id: 0,
1383                 amount_msat: htlc_msat,
1384                 payment_hash: payment_hash,
1385                 cltv_expiry: htlc_cltv,
1386                 onion_routing_packet: onion_packet,
1387         };
1388
1389         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1390
1391         // Now manually create the commitment_signed message corresponding to the update_add
1392         // nodes[0] just sent. In the code for construction of this message, "local" refers
1393         // to the sender of the message, and "remote" refers to the receiver.
1394
1395         let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1396
1397         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1398
1399         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1400         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1401         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1402                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1403                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1404                 let chan_signer = local_chan.get_signer();
1405                 // Make the signer believe we validated another commitment, so we can release the secret
1406                 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1407
1408                 let pubkeys = chan_signer.pubkeys();
1409                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1410                  chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1411                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1412                  chan_signer.pubkeys().funding_pubkey)
1413         };
1414         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1415                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1416                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1417                 let chan_signer = remote_chan.get_signer();
1418                 let pubkeys = chan_signer.pubkeys();
1419                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1420                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1421                  chan_signer.pubkeys().funding_pubkey)
1422         };
1423
1424         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1425         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1426                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1427
1428         // Build the remote commitment transaction so we can sign it, and then later use the
1429         // signature for the commitment_signed message.
1430         let local_chan_balance = 1313;
1431
1432         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1433                 offered: false,
1434                 amount_msat: 3460001,
1435                 cltv_expiry: htlc_cltv,
1436                 payment_hash,
1437                 transaction_output_index: Some(1),
1438         };
1439
1440         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1441
1442         let res = {
1443                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1444                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1445                 let local_chan_signer = local_chan.get_signer();
1446                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1447                         commitment_number,
1448                         95000,
1449                         local_chan_balance,
1450                         local_chan.opt_anchors(), local_funding, remote_funding,
1451                         commit_tx_keys.clone(),
1452                         feerate_per_kw,
1453                         &mut vec![(accepted_htlc_info, ())],
1454                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1455                 );
1456                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1457         };
1458
1459         let commit_signed_msg = msgs::CommitmentSigned {
1460                 channel_id: chan.2,
1461                 signature: res.0,
1462                 htlc_signatures: res.1
1463         };
1464
1465         // Send the commitment_signed message to the nodes[1].
1466         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1467         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1468
1469         // Send the RAA to nodes[1].
1470         let raa_msg = msgs::RevokeAndACK {
1471                 channel_id: chan.2,
1472                 per_commitment_secret: local_secret,
1473                 next_per_commitment_point: next_local_point
1474         };
1475         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1476
1477         let events = nodes[1].node.get_and_clear_pending_msg_events();
1478         assert_eq!(events.len(), 1);
1479         // Make sure the HTLC failed in the way we expect.
1480         match events[0] {
1481                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1482                         assert_eq!(update_fail_htlcs.len(), 1);
1483                         update_fail_htlcs[0].clone()
1484                 },
1485                 _ => panic!("Unexpected event"),
1486         };
1487         nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1488                 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1489
1490         check_added_monitors!(nodes[1], 2);
1491 }
1492
1493 #[test]
1494 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1495         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1496         // Set the fee rate for the channel very high, to the point where the fundee
1497         // sending any above-dust amount would result in a channel reserve violation.
1498         // In this test we check that we would be prevented from sending an HTLC in
1499         // this situation.
1500         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1501         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1502         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1503         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1504         let default_config = UserConfig::default();
1505         let opt_anchors = false;
1506
1507         let mut push_amt = 100_000_000;
1508         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1509
1510         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1511
1512         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1513
1514         // Sending exactly enough to hit the reserve amount should be accepted
1515         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1516                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1517         }
1518
1519         // However one more HTLC should be significantly over the reserve amount and fail.
1520         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1521         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1522                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1523         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1524         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);
1525 }
1526
1527 #[test]
1528 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1529         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1530         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1531         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1532         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1533         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1534         let default_config = UserConfig::default();
1535         let opt_anchors = false;
1536
1537         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1538         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1539         // transaction fee with 0 HTLCs (183 sats)).
1540         let mut push_amt = 100_000_000;
1541         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1542         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1543         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1544
1545         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1546         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1547                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1548         }
1549
1550         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1551         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1552         let secp_ctx = Secp256k1::new();
1553         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1554         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1555         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1556         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 700_000, &Some(payment_secret), cur_height, &None).unwrap();
1557         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1558         let msg = msgs::UpdateAddHTLC {
1559                 channel_id: chan.2,
1560                 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1561                 amount_msat: htlc_msat,
1562                 payment_hash: payment_hash,
1563                 cltv_expiry: htlc_cltv,
1564                 onion_routing_packet: onion_packet,
1565         };
1566
1567         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1568         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1569         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);
1570         assert_eq!(nodes[0].node.list_channels().len(), 0);
1571         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1572         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1573         check_added_monitors!(nodes[0], 1);
1574         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() });
1575 }
1576
1577 #[test]
1578 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1579         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1580         // calculating our commitment transaction fee (this was previously broken).
1581         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1582         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1583
1584         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1585         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1586         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1587         let default_config = UserConfig::default();
1588         let opt_anchors = false;
1589
1590         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1591         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1592         // transaction fee with 0 HTLCs (183 sats)).
1593         let mut push_amt = 100_000_000;
1594         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1595         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1596         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, InitFeatures::known(), InitFeatures::known());
1597
1598         let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1599                 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1600         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1601         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1602         // commitment transaction fee.
1603         let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1604
1605         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1606         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1607                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1608         }
1609
1610         // One more than the dust amt should fail, however.
1611         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1612         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1613                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1614 }
1615
1616 #[test]
1617 fn test_chan_init_feerate_unaffordability() {
1618         // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1619         // channel reserve and feerate requirements.
1620         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1621         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1622         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1623         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1624         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1625         let default_config = UserConfig::default();
1626         let opt_anchors = false;
1627
1628         // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1629         // HTLC.
1630         let mut push_amt = 100_000_000;
1631         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1632         assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1633                 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1634
1635         // During open, we don't have a "counterparty channel reserve" to check against, so that
1636         // requirement only comes into play on the open_channel handling side.
1637         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1638         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1639         let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1640         open_channel_msg.push_msat += 1;
1641         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_msg);
1642
1643         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1644         assert_eq!(msg_events.len(), 1);
1645         match msg_events[0] {
1646                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1647                         assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1648                 },
1649                 _ => panic!("Unexpected event"),
1650         }
1651 }
1652
1653 #[test]
1654 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1655         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1656         // calculating our counterparty's commitment transaction fee (this was previously broken).
1657         let chanmon_cfgs = create_chanmon_cfgs(2);
1658         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1659         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1660         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1661         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1662
1663         let payment_amt = 46000; // Dust amount
1664         // In the previous code, these first four payments would succeed.
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         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1669
1670         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
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         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1676
1677         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1678         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1679         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1680         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1681 }
1682
1683 #[test]
1684 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1685         let chanmon_cfgs = create_chanmon_cfgs(3);
1686         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1687         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1688         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1689         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1690         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1691
1692         let feemsat = 239;
1693         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1694         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1695         let feerate = get_feerate!(nodes[0], chan.2);
1696         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
1697
1698         // Add a 2* and +1 for the fee spike reserve.
1699         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1700         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;
1701         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1702
1703         // Add a pending HTLC.
1704         let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1705         let payment_event_1 = {
1706                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1707                 check_added_monitors!(nodes[0], 1);
1708
1709                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1710                 assert_eq!(events.len(), 1);
1711                 SendEvent::from_event(events.remove(0))
1712         };
1713         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1714
1715         // Attempt to trigger a channel reserve violation --> payment failure.
1716         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1717         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;
1718         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1719         let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1720
1721         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1722         let secp_ctx = Secp256k1::new();
1723         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1724         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1725         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1726         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1727         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1728         let msg = msgs::UpdateAddHTLC {
1729                 channel_id: chan.2,
1730                 htlc_id: 1,
1731                 amount_msat: htlc_msat + 1,
1732                 payment_hash: our_payment_hash_1,
1733                 cltv_expiry: htlc_cltv,
1734                 onion_routing_packet: onion_packet,
1735         };
1736
1737         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1738         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1739         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1740         assert_eq!(nodes[1].node.list_channels().len(), 1);
1741         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1742         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1743         check_added_monitors!(nodes[1], 1);
1744         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1745 }
1746
1747 #[test]
1748 fn test_inbound_outbound_capacity_is_not_zero() {
1749         let chanmon_cfgs = create_chanmon_cfgs(2);
1750         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1751         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1752         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1753         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1754         let channels0 = node_chanmgrs[0].list_channels();
1755         let channels1 = node_chanmgrs[1].list_channels();
1756         let default_config = UserConfig::default();
1757         assert_eq!(channels0.len(), 1);
1758         assert_eq!(channels1.len(), 1);
1759
1760         let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1761         assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1762         assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1763
1764         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1765         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1766 }
1767
1768 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1769         (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1770 }
1771
1772 #[test]
1773 fn test_channel_reserve_holding_cell_htlcs() {
1774         let chanmon_cfgs = create_chanmon_cfgs(3);
1775         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1776         // When this test was written, the default base fee floated based on the HTLC count.
1777         // It is now fixed, so we simply set the fee to the expected value here.
1778         let mut config = test_default_channel_config();
1779         config.channel_config.forwarding_fee_base_msat = 239;
1780         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1781         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1782         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1783         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1784
1785         let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1786         let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1787
1788         let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1789         let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1790
1791         macro_rules! expect_forward {
1792                 ($node: expr) => {{
1793                         let mut events = $node.node.get_and_clear_pending_msg_events();
1794                         assert_eq!(events.len(), 1);
1795                         check_added_monitors!($node, 1);
1796                         let payment_event = SendEvent::from_event(events.remove(0));
1797                         payment_event
1798                 }}
1799         }
1800
1801         let feemsat = 239; // set above
1802         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1803         let feerate = get_feerate!(nodes[0], chan_1.2);
1804         let opt_anchors = get_opt_anchors!(nodes[0], chan_1.2);
1805
1806         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1807
1808         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1809         {
1810                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())
1811                         .with_features(InvoiceFeatures::known()).with_max_channel_saturation_power_of_half(0);
1812                 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);
1813                 route.paths[0].last_mut().unwrap().fee_msat += 1;
1814                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1815
1816                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1817                         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)));
1818                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1819                 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);
1820         }
1821
1822         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1823         // nodes[0]'s wealth
1824         loop {
1825                 let amt_msat = recv_value_0 + total_fee_msat;
1826                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1827                 // Also, ensure that each payment has enough to be over the dust limit to
1828                 // ensure it'll be included in each commit tx fee calculation.
1829                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1830                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1831                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1832                         break;
1833                 }
1834
1835                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())
1836                         .with_features(InvoiceFeatures::known()).with_max_channel_saturation_power_of_half(0);
1837                 let route = get_route!(nodes[0], payment_params, recv_value_0, TEST_FINAL_CLTV).unwrap();
1838                 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1839                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1840
1841                 let (stat01_, stat11_, stat12_, stat22_) = (
1842                         get_channel_value_stat!(nodes[0], chan_1.2),
1843                         get_channel_value_stat!(nodes[1], chan_1.2),
1844                         get_channel_value_stat!(nodes[1], chan_2.2),
1845                         get_channel_value_stat!(nodes[2], chan_2.2),
1846                 );
1847
1848                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1849                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1850                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1851                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1852                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1853         }
1854
1855         // adding pending output.
1856         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1857         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1858         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1859         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1860         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1861         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1862         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1863         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1864         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1865         // policy.
1866         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1867         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1868         let amt_msat_1 = recv_value_1 + total_fee_msat;
1869
1870         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);
1871         let payment_event_1 = {
1872                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1873                 check_added_monitors!(nodes[0], 1);
1874
1875                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1876                 assert_eq!(events.len(), 1);
1877                 SendEvent::from_event(events.remove(0))
1878         };
1879         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1880
1881         // channel reserve test with htlc pending output > 0
1882         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1883         {
1884                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1885                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1886                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1887                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1888         }
1889
1890         // split the rest to test holding cell
1891         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1892         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1893         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1894         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1895         {
1896                 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1897                 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);
1898         }
1899
1900         // now see if they go through on both sides
1901         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);
1902         // but this will stuck in the holding cell
1903         nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21)).unwrap();
1904         check_added_monitors!(nodes[0], 0);
1905         let events = nodes[0].node.get_and_clear_pending_events();
1906         assert_eq!(events.len(), 0);
1907
1908         // test with outbound holding cell amount > 0
1909         {
1910                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1911                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1912                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1913                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1914                 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);
1915         }
1916
1917         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);
1918         // this will also stuck in the holding cell
1919         nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22)).unwrap();
1920         check_added_monitors!(nodes[0], 0);
1921         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1922         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1923
1924         // flush the pending htlc
1925         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1926         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1927         check_added_monitors!(nodes[1], 1);
1928
1929         // the pending htlc should be promoted to committed
1930         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1931         check_added_monitors!(nodes[0], 1);
1932         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1933
1934         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1935         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1936         // No commitment_signed so get_event_msg's assert(len == 1) passes
1937         check_added_monitors!(nodes[0], 1);
1938
1939         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1940         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1941         check_added_monitors!(nodes[1], 1);
1942
1943         expect_pending_htlcs_forwardable!(nodes[1]);
1944
1945         let ref payment_event_11 = expect_forward!(nodes[1]);
1946         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1947         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1948
1949         expect_pending_htlcs_forwardable!(nodes[2]);
1950         expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1951
1952         // flush the htlcs in the holding cell
1953         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1954         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1955         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1956         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1957         expect_pending_htlcs_forwardable!(nodes[1]);
1958
1959         let ref payment_event_3 = expect_forward!(nodes[1]);
1960         assert_eq!(payment_event_3.msgs.len(), 2);
1961         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1962         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1963
1964         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1965         expect_pending_htlcs_forwardable!(nodes[2]);
1966
1967         let events = nodes[2].node.get_and_clear_pending_events();
1968         assert_eq!(events.len(), 2);
1969         match events[0] {
1970                 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
1971                         assert_eq!(our_payment_hash_21, *payment_hash);
1972                         assert_eq!(recv_value_21, amount_msat);
1973                         match &purpose {
1974                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1975                                         assert!(payment_preimage.is_none());
1976                                         assert_eq!(our_payment_secret_21, *payment_secret);
1977                                 },
1978                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1979                         }
1980                 },
1981                 _ => panic!("Unexpected event"),
1982         }
1983         match events[1] {
1984                 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
1985                         assert_eq!(our_payment_hash_22, *payment_hash);
1986                         assert_eq!(recv_value_22, amount_msat);
1987                         match &purpose {
1988                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1989                                         assert!(payment_preimage.is_none());
1990                                         assert_eq!(our_payment_secret_22, *payment_secret);
1991                                 },
1992                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
1993                         }
1994                 },
1995                 _ => panic!("Unexpected event"),
1996         }
1997
1998         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
1999         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2000         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2001
2002         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
2003         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2004         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2005
2006         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
2007         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);
2008         let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2009         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2010         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2011
2012         let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2013         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2014 }
2015
2016 #[test]
2017 fn channel_reserve_in_flight_removes() {
2018         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2019         // can send to its counterparty, but due to update ordering, the other side may not yet have
2020         // considered those HTLCs fully removed.
2021         // This tests that we don't count HTLCs which will not be included in the next remote
2022         // commitment transaction towards the reserve value (as it implies no commitment transaction
2023         // will be generated which violates the remote reserve value).
2024         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2025         // To test this we:
2026         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2027         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2028         //    you only consider the value of the first HTLC, it may not),
2029         //  * start routing a third HTLC from A to B,
2030         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2031         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2032         //  * deliver the first fulfill from B
2033         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2034         //    claim,
2035         //  * deliver A's response CS and RAA.
2036         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2037         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2038         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2039         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2040         let chanmon_cfgs = create_chanmon_cfgs(2);
2041         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2042         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2043         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2044         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2045
2046         let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2047         // Route the first two HTLCs.
2048         let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2049         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2050         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2051
2052         // Start routing the third HTLC (this is just used to get everyone in the right state).
2053         let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2054         let send_1 = {
2055                 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3)).unwrap();
2056                 check_added_monitors!(nodes[0], 1);
2057                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2058                 assert_eq!(events.len(), 1);
2059                 SendEvent::from_event(events.remove(0))
2060         };
2061
2062         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2063         // initial fulfill/CS.
2064         nodes[1].node.claim_funds(payment_preimage_1);
2065         expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2066         check_added_monitors!(nodes[1], 1);
2067         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2068
2069         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2070         // remove the second HTLC when we send the HTLC back from B to A.
2071         nodes[1].node.claim_funds(payment_preimage_2);
2072         expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2073         check_added_monitors!(nodes[1], 1);
2074         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2075
2076         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2077         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2078         check_added_monitors!(nodes[0], 1);
2079         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2080         expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2081
2082         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2083         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2084         check_added_monitors!(nodes[1], 1);
2085         // B is already AwaitingRAA, so cant generate a CS here
2086         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2087
2088         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2089         check_added_monitors!(nodes[1], 1);
2090         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2091
2092         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2093         check_added_monitors!(nodes[0], 1);
2094         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2095
2096         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2097         check_added_monitors!(nodes[1], 1);
2098         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2099
2100         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2101         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2102         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2103         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2104         // on-chain as necessary).
2105         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2106         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2107         check_added_monitors!(nodes[0], 1);
2108         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2109         expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2110
2111         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2112         check_added_monitors!(nodes[1], 1);
2113         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2114
2115         expect_pending_htlcs_forwardable!(nodes[1]);
2116         expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2117
2118         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2119         // resolve the second HTLC from A's point of view.
2120         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2121         check_added_monitors!(nodes[0], 1);
2122         expect_payment_path_successful!(nodes[0]);
2123         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2124
2125         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2126         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2127         let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2128         let send_2 = {
2129                 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4)).unwrap();
2130                 check_added_monitors!(nodes[1], 1);
2131                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2132                 assert_eq!(events.len(), 1);
2133                 SendEvent::from_event(events.remove(0))
2134         };
2135
2136         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2137         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2138         check_added_monitors!(nodes[0], 1);
2139         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2140
2141         // Now just resolve all the outstanding messages/HTLCs for completeness...
2142
2143         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2144         check_added_monitors!(nodes[1], 1);
2145         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2146
2147         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2148         check_added_monitors!(nodes[1], 1);
2149
2150         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2151         check_added_monitors!(nodes[0], 1);
2152         expect_payment_path_successful!(nodes[0]);
2153         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2154
2155         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2156         check_added_monitors!(nodes[1], 1);
2157         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2158
2159         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2160         check_added_monitors!(nodes[0], 1);
2161
2162         expect_pending_htlcs_forwardable!(nodes[0]);
2163         expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2164
2165         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2166         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2167 }
2168
2169 #[test]
2170 fn channel_monitor_network_test() {
2171         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2172         // tests that ChannelMonitor is able to recover from various states.
2173         let chanmon_cfgs = create_chanmon_cfgs(5);
2174         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2175         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2176         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2177
2178         // Create some initial channels
2179         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2180         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2181         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2182         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2183
2184         // Make sure all nodes are at the same starting height
2185         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2186         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2187         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2188         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2189         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2190
2191         // Rebalance the network a bit by relaying one payment through all the channels...
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         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2196
2197         // Simple case with no pending HTLCs:
2198         nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2199         check_added_monitors!(nodes[1], 1);
2200         check_closed_broadcast!(nodes[1], true);
2201         {
2202                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2203                 assert_eq!(node_txn.len(), 1);
2204                 mine_transaction(&nodes[0], &node_txn[0]);
2205                 check_added_monitors!(nodes[0], 1);
2206                 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2207         }
2208         check_closed_broadcast!(nodes[0], true);
2209         assert_eq!(nodes[0].node.list_channels().len(), 0);
2210         assert_eq!(nodes[1].node.list_channels().len(), 1);
2211         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2212         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2213
2214         // One pending HTLC is discarded by the force-close:
2215         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2216
2217         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2218         // broadcasted until we reach the timelock time).
2219         nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2220         check_closed_broadcast!(nodes[1], true);
2221         check_added_monitors!(nodes[1], 1);
2222         {
2223                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2224                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2225                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2226                 mine_transaction(&nodes[2], &node_txn[0]);
2227                 check_added_monitors!(nodes[2], 1);
2228                 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2229         }
2230         check_closed_broadcast!(nodes[2], true);
2231         assert_eq!(nodes[1].node.list_channels().len(), 0);
2232         assert_eq!(nodes[2].node.list_channels().len(), 1);
2233         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2234         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2235
2236         macro_rules! claim_funds {
2237                 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2238                         {
2239                                 $node.node.claim_funds($preimage);
2240                                 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2241                                 check_added_monitors!($node, 1);
2242
2243                                 let events = $node.node.get_and_clear_pending_msg_events();
2244                                 assert_eq!(events.len(), 1);
2245                                 match events[0] {
2246                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2247                                                 assert!(update_add_htlcs.is_empty());
2248                                                 assert!(update_fail_htlcs.is_empty());
2249                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2250                                         },
2251                                         _ => panic!("Unexpected event"),
2252                                 };
2253                         }
2254                 }
2255         }
2256
2257         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2258         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2259         nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2260         check_added_monitors!(nodes[2], 1);
2261         check_closed_broadcast!(nodes[2], true);
2262         let node2_commitment_txid;
2263         {
2264                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2265                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2266                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2267                 node2_commitment_txid = node_txn[0].txid();
2268
2269                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2270                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2271                 mine_transaction(&nodes[3], &node_txn[0]);
2272                 check_added_monitors!(nodes[3], 1);
2273                 check_preimage_claim(&nodes[3], &node_txn);
2274         }
2275         check_closed_broadcast!(nodes[3], true);
2276         assert_eq!(nodes[2].node.list_channels().len(), 0);
2277         assert_eq!(nodes[3].node.list_channels().len(), 1);
2278         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2279         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2280
2281         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2282         // confusing us in the following tests.
2283         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2284
2285         // One pending HTLC to time out:
2286         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2287         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2288         // buffer space).
2289
2290         let (close_chan_update_1, close_chan_update_2) = {
2291                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2292                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2293                 assert_eq!(events.len(), 2);
2294                 let close_chan_update_1 = match events[0] {
2295                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2296                                 msg.clone()
2297                         },
2298                         _ => panic!("Unexpected event"),
2299                 };
2300                 match events[1] {
2301                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2302                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2303                         },
2304                         _ => panic!("Unexpected event"),
2305                 }
2306                 check_added_monitors!(nodes[3], 1);
2307
2308                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2309                 {
2310                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2311                         node_txn.retain(|tx| {
2312                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2313                                         false
2314                                 } else { true }
2315                         });
2316                 }
2317
2318                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2319
2320                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2321                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2322
2323                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2324                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2325                 assert_eq!(events.len(), 2);
2326                 let close_chan_update_2 = match events[0] {
2327                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2328                                 msg.clone()
2329                         },
2330                         _ => panic!("Unexpected event"),
2331                 };
2332                 match events[1] {
2333                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2334                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2335                         },
2336                         _ => panic!("Unexpected event"),
2337                 }
2338                 check_added_monitors!(nodes[4], 1);
2339                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2340
2341                 mine_transaction(&nodes[4], &node_txn[0]);
2342                 check_preimage_claim(&nodes[4], &node_txn);
2343                 (close_chan_update_1, close_chan_update_2)
2344         };
2345         nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2346         nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2347         assert_eq!(nodes[3].node.list_channels().len(), 0);
2348         assert_eq!(nodes[4].node.list_channels().len(), 0);
2349
2350         nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon).unwrap();
2351         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2352         check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2353 }
2354
2355 #[test]
2356 fn test_justice_tx() {
2357         // Test justice txn built on revoked HTLC-Success tx, against both sides
2358         let mut alice_config = UserConfig::default();
2359         alice_config.channel_handshake_config.announced_channel = true;
2360         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2361         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2362         let mut bob_config = UserConfig::default();
2363         bob_config.channel_handshake_config.announced_channel = true;
2364         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2365         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2366         let user_cfgs = [Some(alice_config), Some(bob_config)];
2367         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2368         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2369         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2370         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2371         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2372         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2373         *nodes[0].connect_style.borrow_mut() = ConnectStyle::FullBlockViaListen;
2374         // Create some new channels:
2375         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2376
2377         // A pending HTLC which will be revoked:
2378         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2379         // Get the will-be-revoked local txn from nodes[0]
2380         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2381         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2382         assert_eq!(revoked_local_txn[0].input.len(), 1);
2383         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2384         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2385         assert_eq!(revoked_local_txn[1].input.len(), 1);
2386         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2387         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2388         // Revoke the old state
2389         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2390
2391         {
2392                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2393                 {
2394                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2395                         assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2396                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2397
2398                         check_spends!(node_txn[0], revoked_local_txn[0]);
2399                         node_txn.swap_remove(0);
2400                         node_txn.truncate(1);
2401                 }
2402                 check_added_monitors!(nodes[1], 1);
2403                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2404                 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2405
2406                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2407                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2408                 // Verify broadcast of revoked HTLC-timeout
2409                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2410                 check_added_monitors!(nodes[0], 1);
2411                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2412                 // Broadcast revoked HTLC-timeout on node 1
2413                 mine_transaction(&nodes[1], &node_txn[1]);
2414                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2415         }
2416         get_announce_close_broadcast_events(&nodes, 0, 1);
2417
2418         assert_eq!(nodes[0].node.list_channels().len(), 0);
2419         assert_eq!(nodes[1].node.list_channels().len(), 0);
2420
2421         // We test justice_tx build by A on B's revoked HTLC-Success tx
2422         // Create some new channels:
2423         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2424         {
2425                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2426                 node_txn.clear();
2427         }
2428
2429         // A pending HTLC which will be revoked:
2430         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2431         // Get the will-be-revoked local txn from B
2432         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2433         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2434         assert_eq!(revoked_local_txn[0].input.len(), 1);
2435         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2436         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2437         // Revoke the old state
2438         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2439         {
2440                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2441                 {
2442                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2443                         assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2444                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2445
2446                         check_spends!(node_txn[0], revoked_local_txn[0]);
2447                         node_txn.swap_remove(0);
2448                 }
2449                 check_added_monitors!(nodes[0], 1);
2450                 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2451
2452                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2453                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2454                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2455                 check_added_monitors!(nodes[1], 1);
2456                 mine_transaction(&nodes[0], &node_txn[1]);
2457                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2458                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2459         }
2460         get_announce_close_broadcast_events(&nodes, 0, 1);
2461         assert_eq!(nodes[0].node.list_channels().len(), 0);
2462         assert_eq!(nodes[1].node.list_channels().len(), 0);
2463 }
2464
2465 #[test]
2466 fn revoked_output_claim() {
2467         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2468         // transaction is broadcast by its counterparty
2469         let chanmon_cfgs = create_chanmon_cfgs(2);
2470         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2471         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2472         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2473         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2474         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2475         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2476         assert_eq!(revoked_local_txn.len(), 1);
2477         // Only output is the full channel value back to nodes[0]:
2478         assert_eq!(revoked_local_txn[0].output.len(), 1);
2479         // Send a payment through, updating everyone's latest commitment txn
2480         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2481
2482         // Inform nodes[1] that nodes[0] broadcast a stale tx
2483         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2484         check_added_monitors!(nodes[1], 1);
2485         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2486         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2487         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2488
2489         check_spends!(node_txn[0], revoked_local_txn[0]);
2490         check_spends!(node_txn[1], chan_1.3);
2491
2492         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2493         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2494         get_announce_close_broadcast_events(&nodes, 0, 1);
2495         check_added_monitors!(nodes[0], 1);
2496         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2497 }
2498
2499 #[test]
2500 fn claim_htlc_outputs_shared_tx() {
2501         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2502         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2503         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2504         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2505         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2506         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2507
2508         // Create some new channel:
2509         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2510
2511         // Rebalance the network to generate htlc in the two directions
2512         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2513         // 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
2514         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2515         let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2516
2517         // Get the will-be-revoked local txn from node[0]
2518         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2519         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2520         assert_eq!(revoked_local_txn[0].input.len(), 1);
2521         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2522         assert_eq!(revoked_local_txn[1].input.len(), 1);
2523         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2524         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2525         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2526
2527         //Revoke the old state
2528         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2529
2530         {
2531                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2532                 check_added_monitors!(nodes[0], 1);
2533                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2534                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2535                 check_added_monitors!(nodes[1], 1);
2536                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2537                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2538                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2539
2540                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2541                 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2542
2543                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2544                 check_spends!(node_txn[0], revoked_local_txn[0]);
2545
2546                 let mut witness_lens = BTreeSet::new();
2547                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2548                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2549                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2550                 assert_eq!(witness_lens.len(), 3);
2551                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2552                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2553                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2554
2555                 // Next nodes[1] broadcasts its current local tx state:
2556                 assert_eq!(node_txn[1].input.len(), 1);
2557                 check_spends!(node_txn[1], chan_1.3);
2558
2559                 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2560                 // ANTI_REORG_DELAY confirmations.
2561                 mine_transaction(&nodes[1], &node_txn[0]);
2562                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2563                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2564         }
2565         get_announce_close_broadcast_events(&nodes, 0, 1);
2566         assert_eq!(nodes[0].node.list_channels().len(), 0);
2567         assert_eq!(nodes[1].node.list_channels().len(), 0);
2568 }
2569
2570 #[test]
2571 fn claim_htlc_outputs_single_tx() {
2572         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2573         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2574         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2575         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2576         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2577         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2578
2579         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2580
2581         // Rebalance the network to generate htlc in the two directions
2582         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2583         // 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
2584         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2585         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2586         let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2587
2588         // Get the will-be-revoked local txn from node[0]
2589         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2590
2591         //Revoke the old state
2592         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2593
2594         {
2595                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2596                 check_added_monitors!(nodes[0], 1);
2597                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2598                 check_added_monitors!(nodes[1], 1);
2599                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2600                 let mut events = nodes[0].node.get_and_clear_pending_events();
2601                 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2602                 match events.last().unwrap() {
2603                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2604                         _ => panic!("Unexpected event"),
2605                 }
2606
2607                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2608                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2609
2610                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2611                 assert!(node_txn.len() == 9 || node_txn.len() == 10);
2612
2613                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2614                 assert_eq!(node_txn[0].input.len(), 1);
2615                 check_spends!(node_txn[0], chan_1.3);
2616                 assert_eq!(node_txn[1].input.len(), 1);
2617                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2618                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2619                 check_spends!(node_txn[1], node_txn[0]);
2620
2621                 // Justice transactions are indices 1-2-4
2622                 assert_eq!(node_txn[2].input.len(), 1);
2623                 assert_eq!(node_txn[3].input.len(), 1);
2624                 assert_eq!(node_txn[4].input.len(), 1);
2625
2626                 check_spends!(node_txn[2], revoked_local_txn[0]);
2627                 check_spends!(node_txn[3], revoked_local_txn[0]);
2628                 check_spends!(node_txn[4], revoked_local_txn[0]);
2629
2630                 let mut witness_lens = BTreeSet::new();
2631                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2632                 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2633                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2634                 assert_eq!(witness_lens.len(), 3);
2635                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2636                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2637                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2638
2639                 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2640                 // ANTI_REORG_DELAY confirmations.
2641                 mine_transaction(&nodes[1], &node_txn[2]);
2642                 mine_transaction(&nodes[1], &node_txn[3]);
2643                 mine_transaction(&nodes[1], &node_txn[4]);
2644                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2645                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2646         }
2647         get_announce_close_broadcast_events(&nodes, 0, 1);
2648         assert_eq!(nodes[0].node.list_channels().len(), 0);
2649         assert_eq!(nodes[1].node.list_channels().len(), 0);
2650 }
2651
2652 #[test]
2653 fn test_htlc_on_chain_success() {
2654         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2655         // the preimage backward accordingly. So here we test that ChannelManager is
2656         // broadcasting the right event to other nodes in payment path.
2657         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2658         // A --------------------> B ----------------------> C (preimage)
2659         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2660         // commitment transaction was broadcast.
2661         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2662         // towards B.
2663         // B should be able to claim via preimage if A then broadcasts its local tx.
2664         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2665         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2666         // PaymentSent event).
2667
2668         let chanmon_cfgs = create_chanmon_cfgs(3);
2669         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2670         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2671         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2672
2673         // Create some initial channels
2674         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2675         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2676
2677         // Ensure all nodes are at the same height
2678         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2679         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2680         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2681         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2682
2683         // Rebalance the network a bit by relaying one payment through all the channels...
2684         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2685         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2686
2687         let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2688         let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2689
2690         // Broadcast legit commitment tx from C on B's chain
2691         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2692         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2693         assert_eq!(commitment_tx.len(), 1);
2694         check_spends!(commitment_tx[0], chan_2.3);
2695         nodes[2].node.claim_funds(our_payment_preimage);
2696         expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2697         nodes[2].node.claim_funds(our_payment_preimage_2);
2698         expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2699         check_added_monitors!(nodes[2], 2);
2700         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2701         assert!(updates.update_add_htlcs.is_empty());
2702         assert!(updates.update_fail_htlcs.is_empty());
2703         assert!(updates.update_fail_malformed_htlcs.is_empty());
2704         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2705
2706         mine_transaction(&nodes[2], &commitment_tx[0]);
2707         check_closed_broadcast!(nodes[2], true);
2708         check_added_monitors!(nodes[2], 1);
2709         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2710         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)
2711         assert_eq!(node_txn.len(), 5);
2712         assert_eq!(node_txn[0], node_txn[3]);
2713         assert_eq!(node_txn[1], node_txn[4]);
2714         assert_eq!(node_txn[2], commitment_tx[0]);
2715         check_spends!(node_txn[0], commitment_tx[0]);
2716         check_spends!(node_txn[1], commitment_tx[0]);
2717         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2718         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2719         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2720         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2721         assert_eq!(node_txn[0].lock_time.0, 0);
2722         assert_eq!(node_txn[1].lock_time.0, 0);
2723
2724         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2725         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2726         connect_block(&nodes[1], &Block { header, txdata: node_txn});
2727         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2728         {
2729                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2730                 assert_eq!(added_monitors.len(), 1);
2731                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2732                 added_monitors.clear();
2733         }
2734         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2735         assert_eq!(forwarded_events.len(), 3);
2736         match forwarded_events[0] {
2737                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2738                 _ => panic!("Unexpected event"),
2739         }
2740         let chan_id = Some(chan_1.2);
2741         match forwarded_events[1] {
2742                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2743                         assert_eq!(fee_earned_msat, Some(1000));
2744                         assert_eq!(prev_channel_id, chan_id);
2745                         assert_eq!(claim_from_onchain_tx, true);
2746                         assert_eq!(next_channel_id, Some(chan_2.2));
2747                 },
2748                 _ => panic!()
2749         }
2750         match forwarded_events[2] {
2751                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2752                         assert_eq!(fee_earned_msat, Some(1000));
2753                         assert_eq!(prev_channel_id, chan_id);
2754                         assert_eq!(claim_from_onchain_tx, true);
2755                         assert_eq!(next_channel_id, Some(chan_2.2));
2756                 },
2757                 _ => panic!()
2758         }
2759         let events = nodes[1].node.get_and_clear_pending_msg_events();
2760         {
2761                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2762                 assert_eq!(added_monitors.len(), 2);
2763                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2764                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2765                 added_monitors.clear();
2766         }
2767         assert_eq!(events.len(), 3);
2768         match events[0] {
2769                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2770                 _ => panic!("Unexpected event"),
2771         }
2772         match events[1] {
2773                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2774                 _ => panic!("Unexpected event"),
2775         }
2776
2777         match events[2] {
2778                 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, .. } } => {
2779                         assert!(update_add_htlcs.is_empty());
2780                         assert!(update_fail_htlcs.is_empty());
2781                         assert_eq!(update_fulfill_htlcs.len(), 1);
2782                         assert!(update_fail_malformed_htlcs.is_empty());
2783                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2784                 },
2785                 _ => panic!("Unexpected event"),
2786         };
2787         macro_rules! check_tx_local_broadcast {
2788                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2789                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2790                         assert_eq!(node_txn.len(), 3);
2791                         // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2792                         // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2793                         check_spends!(node_txn[1], $commitment_tx);
2794                         check_spends!(node_txn[2], $commitment_tx);
2795                         assert_ne!(node_txn[1].lock_time.0, 0);
2796                         assert_ne!(node_txn[2].lock_time.0, 0);
2797                         if $htlc_offered {
2798                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2799                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2800                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2801                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2802                         } else {
2803                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2804                                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2805                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2806                                 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2807                         }
2808                         check_spends!(node_txn[0], $chan_tx);
2809                         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2810                         node_txn.clear();
2811                 } }
2812         }
2813         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2814         // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2815         // timeout-claim of the output that nodes[2] just claimed via success.
2816         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2817
2818         // Broadcast legit commitment tx from A on B's chain
2819         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2820         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2821         check_spends!(node_a_commitment_tx[0], chan_1.3);
2822         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2823         check_closed_broadcast!(nodes[1], true);
2824         check_added_monitors!(nodes[1], 1);
2825         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2826         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2827         assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2828         let commitment_spend =
2829                 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2830                         check_spends!(node_txn[1], commitment_tx[0]);
2831                         check_spends!(node_txn[2], commitment_tx[0]);
2832                         assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2833                         &node_txn[0]
2834                 } else {
2835                         check_spends!(node_txn[0], commitment_tx[0]);
2836                         check_spends!(node_txn[1], commitment_tx[0]);
2837                         assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2838                         &node_txn[2]
2839                 };
2840
2841         check_spends!(commitment_spend, node_a_commitment_tx[0]);
2842         assert_eq!(commitment_spend.input.len(), 2);
2843         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2844         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2845         assert_eq!(commitment_spend.lock_time.0, 0);
2846         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2847         check_spends!(node_txn[3], chan_1.3);
2848         assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2849         check_spends!(node_txn[4], node_txn[3]);
2850         check_spends!(node_txn[5], node_txn[3]);
2851         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2852         // we already checked the same situation with A.
2853
2854         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2855         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2856         connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2857         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2858         check_closed_broadcast!(nodes[0], true);
2859         check_added_monitors!(nodes[0], 1);
2860         let events = nodes[0].node.get_and_clear_pending_events();
2861         assert_eq!(events.len(), 5);
2862         let mut first_claimed = false;
2863         for event in events {
2864                 match event {
2865                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2866                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2867                                         assert!(!first_claimed);
2868                                         first_claimed = true;
2869                                 } else {
2870                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2871                                         assert_eq!(payment_hash, payment_hash_2);
2872                                 }
2873                         },
2874                         Event::PaymentPathSuccessful { .. } => {},
2875                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2876                         _ => panic!("Unexpected event"),
2877                 }
2878         }
2879         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2880 }
2881
2882 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2883         // Test that in case of a unilateral close onchain, we detect the state of output and
2884         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2885         // broadcasting the right event to other nodes in payment path.
2886         // A ------------------> B ----------------------> C (timeout)
2887         //    B's commitment tx                 C's commitment tx
2888         //            \                                  \
2889         //         B's HTLC timeout tx               B's timeout tx
2890
2891         let chanmon_cfgs = create_chanmon_cfgs(3);
2892         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2893         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2894         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2895         *nodes[0].connect_style.borrow_mut() = connect_style;
2896         *nodes[1].connect_style.borrow_mut() = connect_style;
2897         *nodes[2].connect_style.borrow_mut() = connect_style;
2898
2899         // Create some intial channels
2900         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2901         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2902
2903         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2904         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2905         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2906
2907         let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2908
2909         // Broadcast legit commitment tx from C on B's chain
2910         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2911         check_spends!(commitment_tx[0], chan_2.3);
2912         nodes[2].node.fail_htlc_backwards(&payment_hash);
2913         check_added_monitors!(nodes[2], 0);
2914         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
2915         check_added_monitors!(nodes[2], 1);
2916
2917         let events = nodes[2].node.get_and_clear_pending_msg_events();
2918         assert_eq!(events.len(), 1);
2919         match events[0] {
2920                 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, .. } } => {
2921                         assert!(update_add_htlcs.is_empty());
2922                         assert!(!update_fail_htlcs.is_empty());
2923                         assert!(update_fulfill_htlcs.is_empty());
2924                         assert!(update_fail_malformed_htlcs.is_empty());
2925                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2926                 },
2927                 _ => panic!("Unexpected event"),
2928         };
2929         mine_transaction(&nodes[2], &commitment_tx[0]);
2930         check_closed_broadcast!(nodes[2], true);
2931         check_added_monitors!(nodes[2], 1);
2932         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2933         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2934         assert_eq!(node_txn.len(), 1);
2935         check_spends!(node_txn[0], chan_2.3);
2936         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2937
2938         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2939         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2940         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2941         mine_transaction(&nodes[1], &commitment_tx[0]);
2942         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2943         let timeout_tx;
2944         {
2945                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2946                 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2947                 assert_eq!(node_txn[0], node_txn[3]);
2948                 assert_eq!(node_txn[1], node_txn[4]);
2949
2950                 check_spends!(node_txn[2], commitment_tx[0]);
2951                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2952
2953                 check_spends!(node_txn[0], chan_2.3);
2954                 check_spends!(node_txn[1], node_txn[0]);
2955                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2956                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2957
2958                 timeout_tx = node_txn[2].clone();
2959                 node_txn.clear();
2960         }
2961
2962         mine_transaction(&nodes[1], &timeout_tx);
2963         check_added_monitors!(nodes[1], 1);
2964         check_closed_broadcast!(nodes[1], true);
2965         {
2966                 // B will rebroadcast a fee-bumped timeout transaction here.
2967                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2968                 assert_eq!(node_txn.len(), 1);
2969                 check_spends!(node_txn[0], commitment_tx[0]);
2970         }
2971
2972         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2973         {
2974                 // B may rebroadcast its own holder commitment transaction here, as a safeguard against
2975                 // some incredibly unlikely partial-eclipse-attack scenarios. That said, because the
2976                 // original commitment_tx[0] (also spending chan_2.3) has reached ANTI_REORG_DELAY B really
2977                 // shouldn't broadcast anything here, and in some connect style scenarios we do not.
2978                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2979                 if node_txn.len() == 1 {
2980                         check_spends!(node_txn[0], chan_2.3);
2981                 } else {
2982                         assert_eq!(node_txn.len(), 0);
2983                 }
2984         }
2985
2986         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 }]);
2987         check_added_monitors!(nodes[1], 1);
2988         let events = nodes[1].node.get_and_clear_pending_msg_events();
2989         assert_eq!(events.len(), 1);
2990         match events[0] {
2991                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
2992                         assert!(update_add_htlcs.is_empty());
2993                         assert!(!update_fail_htlcs.is_empty());
2994                         assert!(update_fulfill_htlcs.is_empty());
2995                         assert!(update_fail_malformed_htlcs.is_empty());
2996                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2997                 },
2998                 _ => panic!("Unexpected event"),
2999         };
3000
3001         // Broadcast legit commitment tx from B on A's chain
3002         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3003         check_spends!(commitment_tx[0], chan_1.3);
3004
3005         mine_transaction(&nodes[0], &commitment_tx[0]);
3006         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
3007
3008         check_closed_broadcast!(nodes[0], true);
3009         check_added_monitors!(nodes[0], 1);
3010         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
3011         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
3012         assert_eq!(node_txn.len(), 2);
3013         check_spends!(node_txn[0], chan_1.3);
3014         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
3015         check_spends!(node_txn[1], commitment_tx[0]);
3016         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3017 }
3018
3019 #[test]
3020 fn test_htlc_on_chain_timeout() {
3021         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3022         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3023         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3024 }
3025
3026 #[test]
3027 fn test_simple_commitment_revoked_fail_backward() {
3028         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3029         // and fail backward accordingly.
3030
3031         let chanmon_cfgs = create_chanmon_cfgs(3);
3032         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3033         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3034         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3035
3036         // Create some initial channels
3037         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3038         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3039
3040         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3041         // Get the will-be-revoked local txn from nodes[2]
3042         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3043         // Revoke the old state
3044         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3045
3046         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3047
3048         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3049         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3050         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3051         check_added_monitors!(nodes[1], 1);
3052         check_closed_broadcast!(nodes[1], true);
3053
3054         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 }]);
3055         check_added_monitors!(nodes[1], 1);
3056         let events = nodes[1].node.get_and_clear_pending_msg_events();
3057         assert_eq!(events.len(), 1);
3058         match events[0] {
3059                 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, .. } } => {
3060                         assert!(update_add_htlcs.is_empty());
3061                         assert_eq!(update_fail_htlcs.len(), 1);
3062                         assert!(update_fulfill_htlcs.is_empty());
3063                         assert!(update_fail_malformed_htlcs.is_empty());
3064                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3065
3066                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3067                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3068                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3069                 },
3070                 _ => panic!("Unexpected event"),
3071         }
3072 }
3073
3074 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3075         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3076         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3077         // commitment transaction anymore.
3078         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3079         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3080         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3081         // technically disallowed and we should probably handle it reasonably.
3082         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3083         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3084         // transactions:
3085         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3086         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3087         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3088         //   and once they revoke the previous commitment transaction (allowing us to send a new
3089         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3090         let chanmon_cfgs = create_chanmon_cfgs(3);
3091         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3092         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3093         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3094
3095         // Create some initial channels
3096         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3097         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3098
3099         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 });
3100         // Get the will-be-revoked local txn from nodes[2]
3101         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3102         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3103         // Revoke the old state
3104         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3105
3106         let value = if use_dust {
3107                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3108                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3109                 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3110         } else { 3000000 };
3111
3112         let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3113         let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3114         let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3115
3116         nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3117         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3118         check_added_monitors!(nodes[2], 1);
3119         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3120         assert!(updates.update_add_htlcs.is_empty());
3121         assert!(updates.update_fulfill_htlcs.is_empty());
3122         assert!(updates.update_fail_malformed_htlcs.is_empty());
3123         assert_eq!(updates.update_fail_htlcs.len(), 1);
3124         assert!(updates.update_fee.is_none());
3125         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3126         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3127         // Drop the last RAA from 3 -> 2
3128
3129         nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3130         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3131         check_added_monitors!(nodes[2], 1);
3132         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3133         assert!(updates.update_add_htlcs.is_empty());
3134         assert!(updates.update_fulfill_htlcs.is_empty());
3135         assert!(updates.update_fail_malformed_htlcs.is_empty());
3136         assert_eq!(updates.update_fail_htlcs.len(), 1);
3137         assert!(updates.update_fee.is_none());
3138         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3139         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3140         check_added_monitors!(nodes[1], 1);
3141         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3142         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3143         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3144         check_added_monitors!(nodes[2], 1);
3145
3146         nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3147         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3148         check_added_monitors!(nodes[2], 1);
3149         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3150         assert!(updates.update_add_htlcs.is_empty());
3151         assert!(updates.update_fulfill_htlcs.is_empty());
3152         assert!(updates.update_fail_malformed_htlcs.is_empty());
3153         assert_eq!(updates.update_fail_htlcs.len(), 1);
3154         assert!(updates.update_fee.is_none());
3155         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3156         // At this point first_payment_hash has dropped out of the latest two commitment
3157         // transactions that nodes[1] is tracking...
3158         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3159         check_added_monitors!(nodes[1], 1);
3160         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3161         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3162         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3163         check_added_monitors!(nodes[2], 1);
3164
3165         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3166         // on nodes[2]'s RAA.
3167         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3168         nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
3169         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3170         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3171         check_added_monitors!(nodes[1], 0);
3172
3173         if deliver_bs_raa {
3174                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3175                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3176                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3177                 check_added_monitors!(nodes[1], 1);
3178                 let events = nodes[1].node.get_and_clear_pending_events();
3179                 assert_eq!(events.len(), 2);
3180                 match events[0] {
3181                         Event::PendingHTLCsForwardable { .. } => { },
3182                         _ => panic!("Unexpected event"),
3183                 };
3184                 match events[1] {
3185                         Event::HTLCHandlingFailed { .. } => { },
3186                         _ => panic!("Unexpected event"),
3187                 }
3188                 // Deliberately don't process the pending fail-back so they all fail back at once after
3189                 // block connection just like the !deliver_bs_raa case
3190         }
3191
3192         let mut failed_htlcs = HashSet::new();
3193         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3194
3195         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3196         check_added_monitors!(nodes[1], 1);
3197         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3198         assert!(ANTI_REORG_DELAY > PAYMENT_EXPIRY_BLOCKS); // We assume payments will also expire
3199
3200         let events = nodes[1].node.get_and_clear_pending_events();
3201         assert_eq!(events.len(), if deliver_bs_raa { 2 + (nodes.len() - 1) } else { 4 + nodes.len() });
3202         match events[0] {
3203                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3204                 _ => panic!("Unexepected event"),
3205         }
3206         match events[1] {
3207                 Event::PaymentPathFailed { ref payment_hash, .. } => {
3208                         assert_eq!(*payment_hash, fourth_payment_hash);
3209                 },
3210                 _ => panic!("Unexpected event"),
3211         }
3212         if !deliver_bs_raa {
3213                 match events[2] {
3214                         Event::PaymentFailed { ref payment_hash, .. } => {
3215                                 assert_eq!(*payment_hash, fourth_payment_hash);
3216                         },
3217                         _ => panic!("Unexpected event"),
3218                 }
3219                 match events[3] {
3220                         Event::PendingHTLCsForwardable { .. } => { },
3221                         _ => panic!("Unexpected event"),
3222                 };
3223         }
3224         nodes[1].node.process_pending_htlc_forwards();
3225         check_added_monitors!(nodes[1], 1);
3226
3227         let events = nodes[1].node.get_and_clear_pending_msg_events();
3228         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3229         match events[if deliver_bs_raa { 1 } else { 0 }] {
3230                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3231                 _ => panic!("Unexpected event"),
3232         }
3233         match events[if deliver_bs_raa { 2 } else { 1 }] {
3234                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3235                         assert_eq!(channel_id, chan_2.2);
3236                         assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3237                 },
3238                 _ => panic!("Unexpected event"),
3239         }
3240         if deliver_bs_raa {
3241                 match events[0] {
3242                         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, .. } } => {
3243                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3244                                 assert_eq!(update_add_htlcs.len(), 1);
3245                                 assert!(update_fulfill_htlcs.is_empty());
3246                                 assert!(update_fail_htlcs.is_empty());
3247                                 assert!(update_fail_malformed_htlcs.is_empty());
3248                         },
3249                         _ => panic!("Unexpected event"),
3250                 }
3251         }
3252         match events[if deliver_bs_raa { 3 } else { 2 }] {
3253                 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, .. } } => {
3254                         assert!(update_add_htlcs.is_empty());
3255                         assert_eq!(update_fail_htlcs.len(), 3);
3256                         assert!(update_fulfill_htlcs.is_empty());
3257                         assert!(update_fail_malformed_htlcs.is_empty());
3258                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3259
3260                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3261                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3262                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3263
3264                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3265
3266                         let events = nodes[0].node.get_and_clear_pending_events();
3267                         assert_eq!(events.len(), 3);
3268                         match events[0] {
3269                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3270                                         assert!(failed_htlcs.insert(payment_hash.0));
3271                                         // If we delivered B's RAA we got an unknown preimage error, not something
3272                                         // that we should update our routing table for.
3273                                         if !deliver_bs_raa {
3274                                                 assert!(network_update.is_some());
3275                                         }
3276                                 },
3277                                 _ => panic!("Unexpected event"),
3278                         }
3279                         match events[1] {
3280                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3281                                         assert!(failed_htlcs.insert(payment_hash.0));
3282                                         assert!(network_update.is_some());
3283                                 },
3284                                 _ => panic!("Unexpected event"),
3285                         }
3286                         match events[2] {
3287                                 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3288                                         assert!(failed_htlcs.insert(payment_hash.0));
3289                                         assert!(network_update.is_some());
3290                                 },
3291                                 _ => panic!("Unexpected event"),
3292                         }
3293                 },
3294                 _ => panic!("Unexpected event"),
3295         }
3296
3297         assert!(failed_htlcs.contains(&first_payment_hash.0));
3298         assert!(failed_htlcs.contains(&second_payment_hash.0));
3299         assert!(failed_htlcs.contains(&third_payment_hash.0));
3300 }
3301
3302 #[test]
3303 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3304         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3305         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3306         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3307         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3308 }
3309
3310 #[test]
3311 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3312         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3313         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3314         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3315         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3316 }
3317
3318 #[test]
3319 fn fail_backward_pending_htlc_upon_channel_failure() {
3320         let chanmon_cfgs = create_chanmon_cfgs(2);
3321         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3322         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3323         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3324         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3325
3326         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3327         {
3328                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3329                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3330                 check_added_monitors!(nodes[0], 1);
3331
3332                 let payment_event = {
3333                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3334                         assert_eq!(events.len(), 1);
3335                         SendEvent::from_event(events.remove(0))
3336                 };
3337                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3338                 assert_eq!(payment_event.msgs.len(), 1);
3339         }
3340
3341         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3342         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3343         {
3344                 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3345                 check_added_monitors!(nodes[0], 0);
3346
3347                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3348         }
3349
3350         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3351         {
3352                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3353
3354                 let secp_ctx = Secp256k1::new();
3355                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3356                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3357                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3358                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3359                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3360
3361                 // Send a 0-msat update_add_htlc to fail the channel.
3362                 let update_add_htlc = msgs::UpdateAddHTLC {
3363                         channel_id: chan.2,
3364                         htlc_id: 0,
3365                         amount_msat: 0,
3366                         payment_hash,
3367                         cltv_expiry,
3368                         onion_routing_packet,
3369                 };
3370                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3371         }
3372         let events = nodes[0].node.get_and_clear_pending_events();
3373         assert_eq!(events.len(), 2);
3374         // Check that Alice fails backward the pending HTLC from the second payment.
3375         match events[0] {
3376                 Event::PaymentPathFailed { payment_hash, .. } => {
3377                         assert_eq!(payment_hash, failed_payment_hash);
3378                 },
3379                 _ => panic!("Unexpected event"),
3380         }
3381         match events[1] {
3382                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3383                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3384                 },
3385                 _ => panic!("Unexpected event {:?}", events[1]),
3386         }
3387         check_closed_broadcast!(nodes[0], true);
3388         check_added_monitors!(nodes[0], 1);
3389 }
3390
3391 #[test]
3392 fn test_htlc_ignore_latest_remote_commitment() {
3393         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3394         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3395         let chanmon_cfgs = create_chanmon_cfgs(2);
3396         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3397         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3398         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3399         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3400
3401         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3402         nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3403         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3404         check_closed_broadcast!(nodes[0], true);
3405         check_added_monitors!(nodes[0], 1);
3406         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3407
3408         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3409         assert_eq!(node_txn.len(), 3);
3410         assert_eq!(node_txn[0], node_txn[1]);
3411
3412         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
3413         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3414         check_closed_broadcast!(nodes[1], true);
3415         check_added_monitors!(nodes[1], 1);
3416         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3417
3418         // Duplicate the connect_block call since this may happen due to other listeners
3419         // registering new transactions
3420         header.prev_blockhash = header.block_hash();
3421         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3422 }
3423
3424 #[test]
3425 fn test_force_close_fail_back() {
3426         // Check which HTLCs are failed-backwards on channel force-closure
3427         let chanmon_cfgs = create_chanmon_cfgs(3);
3428         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3429         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3430         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3431         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3432         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3433
3434         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3435
3436         let mut payment_event = {
3437                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3438                 check_added_monitors!(nodes[0], 1);
3439
3440                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3441                 assert_eq!(events.len(), 1);
3442                 SendEvent::from_event(events.remove(0))
3443         };
3444
3445         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3446         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3447
3448         expect_pending_htlcs_forwardable!(nodes[1]);
3449
3450         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3451         assert_eq!(events_2.len(), 1);
3452         payment_event = SendEvent::from_event(events_2.remove(0));
3453         assert_eq!(payment_event.msgs.len(), 1);
3454
3455         check_added_monitors!(nodes[1], 1);
3456         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3457         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3458         check_added_monitors!(nodes[2], 1);
3459         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3460
3461         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3462         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3463         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3464
3465         nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3466         check_closed_broadcast!(nodes[2], true);
3467         check_added_monitors!(nodes[2], 1);
3468         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3469         let tx = {
3470                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3471                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3472                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3473                 // back to nodes[1] upon timeout otherwise.
3474                 assert_eq!(node_txn.len(), 1);
3475                 node_txn.remove(0)
3476         };
3477
3478         mine_transaction(&nodes[1], &tx);
3479
3480         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3481         check_closed_broadcast!(nodes[1], true);
3482         check_added_monitors!(nodes[1], 1);
3483         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3484
3485         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3486         {
3487                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3488                         .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);
3489         }
3490         mine_transaction(&nodes[2], &tx);
3491         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3492         assert_eq!(node_txn.len(), 1);
3493         assert_eq!(node_txn[0].input.len(), 1);
3494         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3495         assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3496         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3497
3498         check_spends!(node_txn[0], tx);
3499 }
3500
3501 #[test]
3502 fn test_dup_events_on_peer_disconnect() {
3503         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3504         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3505         // as we used to generate the event immediately upon receipt of the payment preimage in the
3506         // update_fulfill_htlc message.
3507
3508         let chanmon_cfgs = create_chanmon_cfgs(2);
3509         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3510         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3511         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3512         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3513
3514         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3515
3516         nodes[1].node.claim_funds(payment_preimage);
3517         expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3518         check_added_monitors!(nodes[1], 1);
3519         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3520         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3521         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3522
3523         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3524         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3525
3526         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3527         expect_payment_path_successful!(nodes[0]);
3528 }
3529
3530 #[test]
3531 fn test_peer_disconnected_before_funding_broadcasted() {
3532         // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3533         // before the funding transaction has been broadcasted.
3534         let chanmon_cfgs = create_chanmon_cfgs(2);
3535         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3536         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3537         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3538
3539         // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3540         // broadcasted, even though it's created by `nodes[0]`.
3541         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();
3542         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3543         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
3544         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3545         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
3546
3547         let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3548         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3549
3550         assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3551
3552         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3553         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3554
3555         // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3556         // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3557         // broadcasted.
3558         {
3559                 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3560         }
3561
3562         // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3563         // disconnected before the funding transaction was broadcasted.
3564         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3565         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3566
3567         check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3568         check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3569 }
3570
3571 #[test]
3572 fn test_simple_peer_disconnect() {
3573         // Test that we can reconnect when there are no lost messages
3574         let chanmon_cfgs = create_chanmon_cfgs(3);
3575         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3576         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3577         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3578         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3579         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3580
3581         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3582         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3583         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3584
3585         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3586         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3587         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3588         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3589
3590         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3591         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3592         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3593
3594         let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3595         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3596         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3597         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3598
3599         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3600         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3601
3602         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3603         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3604
3605         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3606         {
3607                 let events = nodes[0].node.get_and_clear_pending_events();
3608                 assert_eq!(events.len(), 3);
3609                 match events[0] {
3610                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3611                                 assert_eq!(payment_preimage, payment_preimage_3);
3612                                 assert_eq!(payment_hash, payment_hash_3);
3613                         },
3614                         _ => panic!("Unexpected event"),
3615                 }
3616                 match events[1] {
3617                         Event::PaymentPathFailed { payment_hash, rejected_by_dest, .. } => {
3618                                 assert_eq!(payment_hash, payment_hash_5);
3619                                 assert!(rejected_by_dest);
3620                         },
3621                         _ => panic!("Unexpected event"),
3622                 }
3623                 match events[2] {
3624                         Event::PaymentPathSuccessful { .. } => {},
3625                         _ => panic!("Unexpected event"),
3626                 }
3627         }
3628
3629         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3630         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3631 }
3632
3633 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3634         // Test that we can reconnect when in-flight HTLC updates get dropped
3635         let chanmon_cfgs = create_chanmon_cfgs(2);
3636         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3637         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3638         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3639
3640         let mut as_channel_ready = None;
3641         if messages_delivered == 0 {
3642                 let (channel_ready, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3643                 as_channel_ready = Some(channel_ready);
3644                 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3645                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3646                 // it before the channel_reestablish message.
3647         } else {
3648                 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3649         }
3650
3651         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3652
3653         let payment_event = {
3654                 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3655                 check_added_monitors!(nodes[0], 1);
3656
3657                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3658                 assert_eq!(events.len(), 1);
3659                 SendEvent::from_event(events.remove(0))
3660         };
3661         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3662
3663         if messages_delivered < 2 {
3664                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3665         } else {
3666                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3667                 if messages_delivered >= 3 {
3668                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3669                         check_added_monitors!(nodes[1], 1);
3670                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3671
3672                         if messages_delivered >= 4 {
3673                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3674                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3675                                 check_added_monitors!(nodes[0], 1);
3676
3677                                 if messages_delivered >= 5 {
3678                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3679                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3680                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3681                                         check_added_monitors!(nodes[0], 1);
3682
3683                                         if messages_delivered >= 6 {
3684                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3685                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3686                                                 check_added_monitors!(nodes[1], 1);
3687                                         }
3688                                 }
3689                         }
3690                 }
3691         }
3692
3693         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3694         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3695         if messages_delivered < 3 {
3696                 if simulate_broken_lnd {
3697                         // lnd has a long-standing bug where they send a channel_ready prior to a
3698                         // channel_reestablish if you reconnect prior to channel_ready time.
3699                         //
3700                         // Here we simulate that behavior, delivering a channel_ready immediately on
3701                         // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3702                         // in `reconnect_nodes` but we currently don't fail based on that.
3703                         //
3704                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3705                         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3706                 }
3707                 // Even if the channel_ready messages get exchanged, as long as nothing further was
3708                 // received on either side, both sides will need to resend them.
3709                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3710         } else if messages_delivered == 3 {
3711                 // nodes[0] still wants its RAA + commitment_signed
3712                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3713         } else if messages_delivered == 4 {
3714                 // nodes[0] still wants its commitment_signed
3715                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3716         } else if messages_delivered == 5 {
3717                 // nodes[1] still wants its final RAA
3718                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3719         } else if messages_delivered == 6 {
3720                 // Everything was delivered...
3721                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3722         }
3723
3724         let events_1 = nodes[1].node.get_and_clear_pending_events();
3725         assert_eq!(events_1.len(), 1);
3726         match events_1[0] {
3727                 Event::PendingHTLCsForwardable { .. } => { },
3728                 _ => panic!("Unexpected event"),
3729         };
3730
3731         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3732         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3733         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3734
3735         nodes[1].node.process_pending_htlc_forwards();
3736
3737         let events_2 = nodes[1].node.get_and_clear_pending_events();
3738         assert_eq!(events_2.len(), 1);
3739         match events_2[0] {
3740                 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
3741                         assert_eq!(payment_hash_1, *payment_hash);
3742                         assert_eq!(amount_msat, 1_000_000);
3743                         match &purpose {
3744                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3745                                         assert!(payment_preimage.is_none());
3746                                         assert_eq!(payment_secret_1, *payment_secret);
3747                                 },
3748                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3749                         }
3750                 },
3751                 _ => panic!("Unexpected event"),
3752         }
3753
3754         nodes[1].node.claim_funds(payment_preimage_1);
3755         check_added_monitors!(nodes[1], 1);
3756         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3757
3758         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3759         assert_eq!(events_3.len(), 1);
3760         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3761                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3762                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3763                         assert!(updates.update_add_htlcs.is_empty());
3764                         assert!(updates.update_fail_htlcs.is_empty());
3765                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3766                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3767                         assert!(updates.update_fee.is_none());
3768                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3769                 },
3770                 _ => panic!("Unexpected event"),
3771         };
3772
3773         if messages_delivered >= 1 {
3774                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3775
3776                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3777                 assert_eq!(events_4.len(), 1);
3778                 match events_4[0] {
3779                         Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3780                                 assert_eq!(payment_preimage_1, *payment_preimage);
3781                                 assert_eq!(payment_hash_1, *payment_hash);
3782                         },
3783                         _ => panic!("Unexpected event"),
3784                 }
3785
3786                 if messages_delivered >= 2 {
3787                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3788                         check_added_monitors!(nodes[0], 1);
3789                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3790
3791                         if messages_delivered >= 3 {
3792                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3793                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3794                                 check_added_monitors!(nodes[1], 1);
3795
3796                                 if messages_delivered >= 4 {
3797                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3798                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3799                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3800                                         check_added_monitors!(nodes[1], 1);
3801
3802                                         if messages_delivered >= 5 {
3803                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3804                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3805                                                 check_added_monitors!(nodes[0], 1);
3806                                         }
3807                                 }
3808                         }
3809                 }
3810         }
3811
3812         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3813         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3814         if messages_delivered < 2 {
3815                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3816                 if messages_delivered < 1 {
3817                         expect_payment_sent!(nodes[0], payment_preimage_1);
3818                 } else {
3819                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3820                 }
3821         } else if messages_delivered == 2 {
3822                 // nodes[0] still wants its RAA + commitment_signed
3823                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3824         } else if messages_delivered == 3 {
3825                 // nodes[0] still wants its commitment_signed
3826                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3827         } else if messages_delivered == 4 {
3828                 // nodes[1] still wants its final RAA
3829                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3830         } else if messages_delivered == 5 {
3831                 // Everything was delivered...
3832                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3833         }
3834
3835         if messages_delivered == 1 || messages_delivered == 2 {
3836                 expect_payment_path_successful!(nodes[0]);
3837         }
3838
3839         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3840         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3841         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3842
3843         if messages_delivered > 2 {
3844                 expect_payment_path_successful!(nodes[0]);
3845         }
3846
3847         // Channel should still work fine...
3848         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3849         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3850         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3851 }
3852
3853 #[test]
3854 fn test_drop_messages_peer_disconnect_a() {
3855         do_test_drop_messages_peer_disconnect(0, true);
3856         do_test_drop_messages_peer_disconnect(0, false);
3857         do_test_drop_messages_peer_disconnect(1, false);
3858         do_test_drop_messages_peer_disconnect(2, false);
3859 }
3860
3861 #[test]
3862 fn test_drop_messages_peer_disconnect_b() {
3863         do_test_drop_messages_peer_disconnect(3, false);
3864         do_test_drop_messages_peer_disconnect(4, false);
3865         do_test_drop_messages_peer_disconnect(5, false);
3866         do_test_drop_messages_peer_disconnect(6, false);
3867 }
3868
3869 #[test]
3870 fn test_funding_peer_disconnect() {
3871         // Test that we can lock in our funding tx while disconnected
3872         let chanmon_cfgs = create_chanmon_cfgs(2);
3873         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3874         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3875         let persister: test_utils::TestPersister;
3876         let new_chain_monitor: test_utils::TestChainMonitor;
3877         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3878         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3879         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3880
3881         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3882         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3883
3884         confirm_transaction(&nodes[0], &tx);
3885         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3886         assert!(events_1.is_empty());
3887
3888         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3889
3890         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3891         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3892
3893         confirm_transaction(&nodes[1], &tx);
3894         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3895         assert!(events_2.is_empty());
3896
3897         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3898         let as_reestablish = get_chan_reestablish_msgs!(nodes[0], nodes[1]).pop().unwrap();
3899         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3900         let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
3901
3902         // nodes[0] hasn't yet received a channel_ready, so it only sends that on reconnect.
3903         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
3904         let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3905         assert_eq!(events_3.len(), 1);
3906         let as_channel_ready = match events_3[0] {
3907                 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
3908                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3909                         msg.clone()
3910                 },
3911                 _ => panic!("Unexpected event {:?}", events_3[0]),
3912         };
3913
3914         // nodes[1] received nodes[0]'s channel_ready on the first reconnect above, so it should send
3915         // announcement_signatures as well as channel_update.
3916         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
3917         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3918         assert_eq!(events_4.len(), 3);
3919         let chan_id;
3920         let bs_channel_ready = match events_4[0] {
3921                 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
3922                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3923                         chan_id = msg.channel_id;
3924                         msg.clone()
3925                 },
3926                 _ => panic!("Unexpected event {:?}", events_4[0]),
3927         };
3928         let bs_announcement_sigs = match events_4[1] {
3929                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3930                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3931                         msg.clone()
3932                 },
3933                 _ => panic!("Unexpected event {:?}", events_4[1]),
3934         };
3935         match events_4[2] {
3936                 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3937                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3938                 },
3939                 _ => panic!("Unexpected event {:?}", events_4[2]),
3940         }
3941
3942         // Re-deliver nodes[0]'s channel_ready, which nodes[1] can safely ignore. It currently
3943         // generates a duplicative private channel_update
3944         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3945         let events_5 = nodes[1].node.get_and_clear_pending_msg_events();
3946         assert_eq!(events_5.len(), 1);
3947         match events_5[0] {
3948                 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3949                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3950                 },
3951                 _ => panic!("Unexpected event {:?}", events_5[0]),
3952         };
3953
3954         // When we deliver nodes[1]'s channel_ready, however, nodes[0] will generate its
3955         // announcement_signatures.
3956         nodes[0].node.handle_channel_ready(&nodes[1].node.get_our_node_id(), &bs_channel_ready);
3957         let events_6 = nodes[0].node.get_and_clear_pending_msg_events();
3958         assert_eq!(events_6.len(), 1);
3959         let as_announcement_sigs = match events_6[0] {
3960                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3961                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3962                         msg.clone()
3963                 },
3964                 _ => panic!("Unexpected event {:?}", events_6[0]),
3965         };
3966
3967         // When we deliver nodes[1]'s announcement_signatures to nodes[0], nodes[0] should immediately
3968         // broadcast the channel announcement globally, as well as re-send its (now-public)
3969         // channel_update.
3970         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3971         let events_7 = nodes[0].node.get_and_clear_pending_msg_events();
3972         assert_eq!(events_7.len(), 1);
3973         let (chan_announcement, as_update) = match events_7[0] {
3974                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3975                         (msg.clone(), update_msg.clone())
3976                 },
3977                 _ => panic!("Unexpected event {:?}", events_7[0]),
3978         };
3979
3980         // Finally, deliver nodes[0]'s announcement_signatures to nodes[1] and make sure it creates the
3981         // same channel_announcement.
3982         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3983         let events_8 = nodes[1].node.get_and_clear_pending_msg_events();
3984         assert_eq!(events_8.len(), 1);
3985         let bs_update = match events_8[0] {
3986                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3987                         assert_eq!(*msg, chan_announcement);
3988                         update_msg.clone()
3989                 },
3990                 _ => panic!("Unexpected event {:?}", events_8[0]),
3991         };
3992
3993         // Provide the channel announcement and public updates to the network graph
3994         nodes[0].gossip_sync.handle_channel_announcement(&chan_announcement).unwrap();
3995         nodes[0].gossip_sync.handle_channel_update(&bs_update).unwrap();
3996         nodes[0].gossip_sync.handle_channel_update(&as_update).unwrap();
3997
3998         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3999         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
4000         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
4001
4002         // Check that after deserialization and reconnection we can still generate an identical
4003         // channel_announcement from the cached signatures.
4004         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4005
4006         let nodes_0_serialized = nodes[0].node.encode();
4007         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4008         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4009
4010         persister = test_utils::TestPersister::new();
4011         let keys_manager = &chanmon_cfgs[0].keys_manager;
4012         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);
4013         nodes[0].chain_monitor = &new_chain_monitor;
4014         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4015         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4016                 &mut chan_0_monitor_read, keys_manager).unwrap();
4017         assert!(chan_0_monitor_read.is_empty());
4018
4019         let mut nodes_0_read = &nodes_0_serialized[..];
4020         let (_, nodes_0_deserialized_tmp) = {
4021                 let mut channel_monitors = HashMap::new();
4022                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4023                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4024                         default_config: UserConfig::default(),
4025                         keys_manager,
4026                         fee_estimator: node_cfgs[0].fee_estimator,
4027                         chain_monitor: nodes[0].chain_monitor,
4028                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4029                         logger: nodes[0].logger,
4030                         channel_monitors,
4031                 }).unwrap()
4032         };
4033         nodes_0_deserialized = nodes_0_deserialized_tmp;
4034         assert!(nodes_0_read.is_empty());
4035
4036         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4037         nodes[0].node = &nodes_0_deserialized;
4038         check_added_monitors!(nodes[0], 1);
4039
4040         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4041 }
4042
4043 #[test]
4044 fn test_channel_ready_without_best_block_updated() {
4045         // Previously, if we were offline when a funding transaction was locked in, and then we came
4046         // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
4047         // generate a channel_ready until a later best_block_updated. This tests that we generate the
4048         // channel_ready immediately instead.
4049         let chanmon_cfgs = create_chanmon_cfgs(2);
4050         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4051         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4052         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4053         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
4054
4055         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
4056
4057         let conf_height = nodes[0].best_block_info().1 + 1;
4058         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4059         let block_txn = [funding_tx];
4060         let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
4061         let conf_block_header = nodes[0].get_block_header(conf_height);
4062         nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
4063
4064         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4065         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4066         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4067 }
4068
4069 #[test]
4070 fn test_drop_messages_peer_disconnect_dual_htlc() {
4071         // Test that we can handle reconnecting when both sides of a channel have pending
4072         // commitment_updates when we disconnect.
4073         let chanmon_cfgs = create_chanmon_cfgs(2);
4074         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4075         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4076         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4077         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4078
4079         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
4080
4081         // Now try to send a second payment which will fail to send
4082         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4083         nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
4084         check_added_monitors!(nodes[0], 1);
4085
4086         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4087         assert_eq!(events_1.len(), 1);
4088         match events_1[0] {
4089                 MessageSendEvent::UpdateHTLCs { .. } => {},
4090                 _ => panic!("Unexpected event"),
4091         }
4092
4093         nodes[1].node.claim_funds(payment_preimage_1);
4094         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4095         check_added_monitors!(nodes[1], 1);
4096
4097         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4098         assert_eq!(events_2.len(), 1);
4099         match events_2[0] {
4100                 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 } } => {
4101                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4102                         assert!(update_add_htlcs.is_empty());
4103                         assert_eq!(update_fulfill_htlcs.len(), 1);
4104                         assert!(update_fail_htlcs.is_empty());
4105                         assert!(update_fail_malformed_htlcs.is_empty());
4106                         assert!(update_fee.is_none());
4107
4108                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4109                         let events_3 = nodes[0].node.get_and_clear_pending_events();
4110                         assert_eq!(events_3.len(), 1);
4111                         match events_3[0] {
4112                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4113                                         assert_eq!(*payment_preimage, payment_preimage_1);
4114                                         assert_eq!(*payment_hash, payment_hash_1);
4115                                 },
4116                                 _ => panic!("Unexpected event"),
4117                         }
4118
4119                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4120                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4121                         // No commitment_signed so get_event_msg's assert(len == 1) passes
4122                         check_added_monitors!(nodes[0], 1);
4123                 },
4124                 _ => panic!("Unexpected event"),
4125         }
4126
4127         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4128         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4129
4130         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4131         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4132         assert_eq!(reestablish_1.len(), 1);
4133         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4134         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4135         assert_eq!(reestablish_2.len(), 1);
4136
4137         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4138         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4139         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4140         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4141
4142         assert!(as_resp.0.is_none());
4143         assert!(bs_resp.0.is_none());
4144
4145         assert!(bs_resp.1.is_none());
4146         assert!(bs_resp.2.is_none());
4147
4148         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4149
4150         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4151         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4152         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4153         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4154         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4155         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4156         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4157         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4158         // No commitment_signed so get_event_msg's assert(len == 1) passes
4159         check_added_monitors!(nodes[1], 1);
4160
4161         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4162         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4163         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4164         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4165         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4166         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4167         assert!(bs_second_commitment_signed.update_fee.is_none());
4168         check_added_monitors!(nodes[1], 1);
4169
4170         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4171         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4172         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4173         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4174         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4175         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4176         assert!(as_commitment_signed.update_fee.is_none());
4177         check_added_monitors!(nodes[0], 1);
4178
4179         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4180         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4181         // No commitment_signed so get_event_msg's assert(len == 1) passes
4182         check_added_monitors!(nodes[0], 1);
4183
4184         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4185         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4186         // No commitment_signed so get_event_msg's assert(len == 1) passes
4187         check_added_monitors!(nodes[1], 1);
4188
4189         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4190         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4191         check_added_monitors!(nodes[1], 1);
4192
4193         expect_pending_htlcs_forwardable!(nodes[1]);
4194
4195         let events_5 = nodes[1].node.get_and_clear_pending_events();
4196         assert_eq!(events_5.len(), 1);
4197         match events_5[0] {
4198                 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
4199                         assert_eq!(payment_hash_2, *payment_hash);
4200                         match &purpose {
4201                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4202                                         assert!(payment_preimage.is_none());
4203                                         assert_eq!(payment_secret_2, *payment_secret);
4204                                 },
4205                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
4206                         }
4207                 },
4208                 _ => panic!("Unexpected event"),
4209         }
4210
4211         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4212         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4213         check_added_monitors!(nodes[0], 1);
4214
4215         expect_payment_path_successful!(nodes[0]);
4216         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4217 }
4218
4219 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4220         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4221         // to avoid our counterparty failing the channel.
4222         let chanmon_cfgs = create_chanmon_cfgs(2);
4223         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4224         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4225         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4226
4227         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4228
4229         let our_payment_hash = if send_partial_mpp {
4230                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4231                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4232                 // indicates there are more HTLCs coming.
4233                 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.
4234                 let payment_id = PaymentId([42; 32]);
4235                 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();
4236                 check_added_monitors!(nodes[0], 1);
4237                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4238                 assert_eq!(events.len(), 1);
4239                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4240                 // hop should *not* yet generate any PaymentReceived event(s).
4241                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4242                 our_payment_hash
4243         } else {
4244                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4245         };
4246
4247         let mut block = Block {
4248                 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
4249                 txdata: vec![],
4250         };
4251         connect_block(&nodes[0], &block);
4252         connect_block(&nodes[1], &block);
4253         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4254         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4255                 block.header.prev_blockhash = block.block_hash();
4256                 connect_block(&nodes[0], &block);
4257                 connect_block(&nodes[1], &block);
4258         }
4259
4260         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4261
4262         check_added_monitors!(nodes[1], 1);
4263         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4264         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4265         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4266         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4267         assert!(htlc_timeout_updates.update_fee.is_none());
4268
4269         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4270         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4271         // 100_000 msat as u64, followed by the height at which we failed back above
4272         let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4273         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
4274         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4275 }
4276
4277 #[test]
4278 fn test_htlc_timeout() {
4279         do_test_htlc_timeout(true);
4280         do_test_htlc_timeout(false);
4281 }
4282
4283 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4284         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4285         let chanmon_cfgs = create_chanmon_cfgs(3);
4286         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4287         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4288         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4289         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4290         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4291
4292         // Make sure all nodes are at the same starting height
4293         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4294         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4295         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4296
4297         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4298         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4299         {
4300                 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
4301         }
4302         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4303         check_added_monitors!(nodes[1], 1);
4304
4305         // Now attempt to route a second payment, which should be placed in the holding cell
4306         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4307         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4308         sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
4309         if forwarded_htlc {
4310                 check_added_monitors!(nodes[0], 1);
4311                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4312                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4313                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4314                 expect_pending_htlcs_forwardable!(nodes[1]);
4315         }
4316         check_added_monitors!(nodes[1], 0);
4317
4318         connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4319         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4320         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4321         connect_blocks(&nodes[1], 1);
4322
4323         if forwarded_htlc {
4324                 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 }]);
4325                 check_added_monitors!(nodes[1], 1);
4326                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4327                 assert_eq!(fail_commit.len(), 1);
4328                 match fail_commit[0] {
4329                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4330                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4331                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4332                         },
4333                         _ => unreachable!(),
4334                 }
4335                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4336         } else {
4337                 let events = nodes[1].node.get_and_clear_pending_events();
4338                 assert_eq!(events.len(), 2);
4339                 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
4340                         assert_eq!(*payment_hash, second_payment_hash);
4341                 } else { panic!("Unexpected event"); }
4342                 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
4343                         assert_eq!(*payment_hash, second_payment_hash);
4344                 } else { panic!("Unexpected event"); }
4345         }
4346 }
4347
4348 #[test]
4349 fn test_holding_cell_htlc_add_timeouts() {
4350         do_test_holding_cell_htlc_add_timeouts(false);
4351         do_test_holding_cell_htlc_add_timeouts(true);
4352 }
4353
4354 #[test]
4355 fn test_no_txn_manager_serialize_deserialize() {
4356         let chanmon_cfgs = create_chanmon_cfgs(2);
4357         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4358         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4359         let logger: test_utils::TestLogger;
4360         let fee_estimator: test_utils::TestFeeEstimator;
4361         let persister: test_utils::TestPersister;
4362         let new_chain_monitor: test_utils::TestChainMonitor;
4363         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4364         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4365
4366         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4367
4368         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4369
4370         let nodes_0_serialized = nodes[0].node.encode();
4371         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4372         get_monitor!(nodes[0], OutPoint { txid: tx.txid(), index: 0 }.to_channel_id())
4373                 .write(&mut chan_0_monitor_serialized).unwrap();
4374
4375         logger = test_utils::TestLogger::new();
4376         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4377         persister = test_utils::TestPersister::new();
4378         let keys_manager = &chanmon_cfgs[0].keys_manager;
4379         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4380         nodes[0].chain_monitor = &new_chain_monitor;
4381         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4382         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4383                 &mut chan_0_monitor_read, keys_manager).unwrap();
4384         assert!(chan_0_monitor_read.is_empty());
4385
4386         let mut nodes_0_read = &nodes_0_serialized[..];
4387         let config = UserConfig::default();
4388         let (_, nodes_0_deserialized_tmp) = {
4389                 let mut channel_monitors = HashMap::new();
4390                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4391                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4392                         default_config: config,
4393                         keys_manager,
4394                         fee_estimator: &fee_estimator,
4395                         chain_monitor: nodes[0].chain_monitor,
4396                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4397                         logger: &logger,
4398                         channel_monitors,
4399                 }).unwrap()
4400         };
4401         nodes_0_deserialized = nodes_0_deserialized_tmp;
4402         assert!(nodes_0_read.is_empty());
4403
4404         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4405         nodes[0].node = &nodes_0_deserialized;
4406         assert_eq!(nodes[0].node.list_channels().len(), 1);
4407         check_added_monitors!(nodes[0], 1);
4408
4409         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4410         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4411         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4412         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4413
4414         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4415         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4416         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4417         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4418
4419         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4420         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
4421         for node in nodes.iter() {
4422                 assert!(node.gossip_sync.handle_channel_announcement(&announcement).unwrap());
4423                 node.gossip_sync.handle_channel_update(&as_update).unwrap();
4424                 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
4425         }
4426
4427         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4428 }
4429
4430 #[test]
4431 fn test_manager_serialize_deserialize_events() {
4432         // This test makes sure the events field in ChannelManager survives de/serialization
4433         let chanmon_cfgs = create_chanmon_cfgs(2);
4434         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4435         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4436         let fee_estimator: test_utils::TestFeeEstimator;
4437         let persister: test_utils::TestPersister;
4438         let logger: test_utils::TestLogger;
4439         let new_chain_monitor: test_utils::TestChainMonitor;
4440         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4441         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4442
4443         // Start creating a channel, but stop right before broadcasting the funding transaction
4444         let channel_value = 100000;
4445         let push_msat = 10001;
4446         let a_flags = InitFeatures::known();
4447         let b_flags = InitFeatures::known();
4448         let node_a = nodes.remove(0);
4449         let node_b = nodes.remove(0);
4450         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4451         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()));
4452         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()));
4453
4454         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, &node_b.node.get_our_node_id(), channel_value, 42);
4455
4456         node_a.node.funding_transaction_generated(&temporary_channel_id, &node_b.node.get_our_node_id(), tx.clone()).unwrap();
4457         check_added_monitors!(node_a, 0);
4458
4459         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()));
4460         {
4461                 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4462                 assert_eq!(added_monitors.len(), 1);
4463                 assert_eq!(added_monitors[0].0, funding_output);
4464                 added_monitors.clear();
4465         }
4466
4467         let bs_funding_signed = get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id());
4468         node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &bs_funding_signed);
4469         {
4470                 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4471                 assert_eq!(added_monitors.len(), 1);
4472                 assert_eq!(added_monitors[0].0, funding_output);
4473                 added_monitors.clear();
4474         }
4475         // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4476
4477         nodes.push(node_a);
4478         nodes.push(node_b);
4479
4480         // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4481         let nodes_0_serialized = nodes[0].node.encode();
4482         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4483         get_monitor!(nodes[0], bs_funding_signed.channel_id).write(&mut chan_0_monitor_serialized).unwrap();
4484
4485         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4486         logger = test_utils::TestLogger::new();
4487         persister = test_utils::TestPersister::new();
4488         let keys_manager = &chanmon_cfgs[0].keys_manager;
4489         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4490         nodes[0].chain_monitor = &new_chain_monitor;
4491         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4492         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4493                 &mut chan_0_monitor_read, keys_manager).unwrap();
4494         assert!(chan_0_monitor_read.is_empty());
4495
4496         let mut nodes_0_read = &nodes_0_serialized[..];
4497         let config = UserConfig::default();
4498         let (_, nodes_0_deserialized_tmp) = {
4499                 let mut channel_monitors = HashMap::new();
4500                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4501                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4502                         default_config: config,
4503                         keys_manager,
4504                         fee_estimator: &fee_estimator,
4505                         chain_monitor: nodes[0].chain_monitor,
4506                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4507                         logger: &logger,
4508                         channel_monitors,
4509                 }).unwrap()
4510         };
4511         nodes_0_deserialized = nodes_0_deserialized_tmp;
4512         assert!(nodes_0_read.is_empty());
4513
4514         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4515
4516         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4517         nodes[0].node = &nodes_0_deserialized;
4518
4519         // After deserializing, make sure the funding_transaction is still held by the channel manager
4520         let events_4 = nodes[0].node.get_and_clear_pending_events();
4521         assert_eq!(events_4.len(), 0);
4522         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4523         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4524
4525         // Make sure the channel is functioning as though the de/serialization never happened
4526         assert_eq!(nodes[0].node.list_channels().len(), 1);
4527         check_added_monitors!(nodes[0], 1);
4528
4529         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4530         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4531         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4532         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4533
4534         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4535         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4536         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4537         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4538
4539         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4540         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
4541         for node in nodes.iter() {
4542                 assert!(node.gossip_sync.handle_channel_announcement(&announcement).unwrap());
4543                 node.gossip_sync.handle_channel_update(&as_update).unwrap();
4544                 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
4545         }
4546
4547         send_payment(&nodes[0], &[&nodes[1]], 1000000);
4548 }
4549
4550 #[test]
4551 fn test_simple_manager_serialize_deserialize() {
4552         let chanmon_cfgs = create_chanmon_cfgs(2);
4553         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4554         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4555         let logger: test_utils::TestLogger;
4556         let fee_estimator: test_utils::TestFeeEstimator;
4557         let persister: test_utils::TestPersister;
4558         let new_chain_monitor: test_utils::TestChainMonitor;
4559         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4560         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4561         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4562
4563         let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4564         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4565
4566         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4567
4568         let nodes_0_serialized = nodes[0].node.encode();
4569         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4570         get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4571
4572         logger = test_utils::TestLogger::new();
4573         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4574         persister = test_utils::TestPersister::new();
4575         let keys_manager = &chanmon_cfgs[0].keys_manager;
4576         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4577         nodes[0].chain_monitor = &new_chain_monitor;
4578         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4579         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4580                 &mut chan_0_monitor_read, keys_manager).unwrap();
4581         assert!(chan_0_monitor_read.is_empty());
4582
4583         let mut nodes_0_read = &nodes_0_serialized[..];
4584         let (_, nodes_0_deserialized_tmp) = {
4585                 let mut channel_monitors = HashMap::new();
4586                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4587                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4588                         default_config: UserConfig::default(),
4589                         keys_manager,
4590                         fee_estimator: &fee_estimator,
4591                         chain_monitor: nodes[0].chain_monitor,
4592                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4593                         logger: &logger,
4594                         channel_monitors,
4595                 }).unwrap()
4596         };
4597         nodes_0_deserialized = nodes_0_deserialized_tmp;
4598         assert!(nodes_0_read.is_empty());
4599
4600         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4601         nodes[0].node = &nodes_0_deserialized;
4602         check_added_monitors!(nodes[0], 1);
4603
4604         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4605
4606         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4607         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4608 }
4609
4610 #[test]
4611 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4612         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4613         let chanmon_cfgs = create_chanmon_cfgs(4);
4614         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4615         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4616         let logger: test_utils::TestLogger;
4617         let fee_estimator: test_utils::TestFeeEstimator;
4618         let persister: test_utils::TestPersister;
4619         let new_chain_monitor: test_utils::TestChainMonitor;
4620         let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4621         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4622         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4623         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known()).2;
4624         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4625
4626         let mut node_0_stale_monitors_serialized = Vec::new();
4627         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4628                 let mut writer = test_utils::TestVecWriter(Vec::new());
4629                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4630                 node_0_stale_monitors_serialized.push(writer.0);
4631         }
4632
4633         let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4634
4635         // Serialize the ChannelManager here, but the monitor we keep up-to-date
4636         let nodes_0_serialized = nodes[0].node.encode();
4637
4638         route_payment(&nodes[0], &[&nodes[3]], 1000000);
4639         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4640         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4641         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4642
4643         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4644         // nodes[3])
4645         let mut node_0_monitors_serialized = Vec::new();
4646         for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4647                 let mut writer = test_utils::TestVecWriter(Vec::new());
4648                 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4649                 node_0_monitors_serialized.push(writer.0);
4650         }
4651
4652         logger = test_utils::TestLogger::new();
4653         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4654         persister = test_utils::TestPersister::new();
4655         let keys_manager = &chanmon_cfgs[0].keys_manager;
4656         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4657         nodes[0].chain_monitor = &new_chain_monitor;
4658
4659
4660         let mut node_0_stale_monitors = Vec::new();
4661         for serialized in node_0_stale_monitors_serialized.iter() {
4662                 let mut read = &serialized[..];
4663                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4664                 assert!(read.is_empty());
4665                 node_0_stale_monitors.push(monitor);
4666         }
4667
4668         let mut node_0_monitors = Vec::new();
4669         for serialized in node_0_monitors_serialized.iter() {
4670                 let mut read = &serialized[..];
4671                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4672                 assert!(read.is_empty());
4673                 node_0_monitors.push(monitor);
4674         }
4675
4676         let mut nodes_0_read = &nodes_0_serialized[..];
4677         if let Err(msgs::DecodeError::InvalidValue) =
4678                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4679                 default_config: UserConfig::default(),
4680                 keys_manager,
4681                 fee_estimator: &fee_estimator,
4682                 chain_monitor: nodes[0].chain_monitor,
4683                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4684                 logger: &logger,
4685                 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4686         }) { } else {
4687                 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4688         };
4689
4690         let mut nodes_0_read = &nodes_0_serialized[..];
4691         let (_, nodes_0_deserialized_tmp) =
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_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4700         }).unwrap();
4701         nodes_0_deserialized = nodes_0_deserialized_tmp;
4702         assert!(nodes_0_read.is_empty());
4703
4704         { // Channel close should result in a commitment tx
4705                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4706                 assert_eq!(txn.len(), 1);
4707                 check_spends!(txn[0], funding_tx);
4708                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4709         }
4710
4711         for monitor in node_0_monitors.drain(..) {
4712                 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4713                 check_added_monitors!(nodes[0], 1);
4714         }
4715         nodes[0].node = &nodes_0_deserialized;
4716         check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4717
4718         // nodes[1] and nodes[2] have no lost state with nodes[0]...
4719         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4720         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4721         //... and we can even still claim the payment!
4722         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4723
4724         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4725         let reestablish = get_chan_reestablish_msgs!(nodes[3], nodes[0]).pop().unwrap();
4726         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4727         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4728         let mut found_err = false;
4729         for msg_event in nodes[0].node.get_and_clear_pending_msg_events() {
4730                 if let MessageSendEvent::HandleError { ref action, .. } = msg_event {
4731                         match action {
4732                                 &ErrorAction::SendErrorMessage { ref msg } => {
4733                                         assert_eq!(msg.channel_id, channel_id);
4734                                         assert!(!found_err);
4735                                         found_err = true;
4736                                 },
4737                                 _ => panic!("Unexpected event!"),
4738                         }
4739                 }
4740         }
4741         assert!(found_err);
4742 }
4743
4744 macro_rules! check_spendable_outputs {
4745         ($node: expr, $keysinterface: expr) => {
4746                 {
4747                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4748                         let mut txn = Vec::new();
4749                         let mut all_outputs = Vec::new();
4750                         let secp_ctx = Secp256k1::new();
4751                         for event in events.drain(..) {
4752                                 match event {
4753                                         Event::SpendableOutputs { mut outputs } => {
4754                                                 for outp in outputs.drain(..) {
4755                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4756                                                         all_outputs.push(outp);
4757                                                 }
4758                                         },
4759                                         _ => panic!("Unexpected event"),
4760                                 };
4761                         }
4762                         if all_outputs.len() > 1 {
4763                                 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) {
4764                                         txn.push(tx);
4765                                 }
4766                         }
4767                         txn
4768                 }
4769         }
4770 }
4771
4772 #[test]
4773 fn test_claim_sizeable_push_msat() {
4774         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4775         let chanmon_cfgs = create_chanmon_cfgs(2);
4776         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4777         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4778         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4779
4780         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4781         nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4782         check_closed_broadcast!(nodes[1], true);
4783         check_added_monitors!(nodes[1], 1);
4784         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4785         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4786         assert_eq!(node_txn.len(), 1);
4787         check_spends!(node_txn[0], chan.3);
4788         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
4789
4790         mine_transaction(&nodes[1], &node_txn[0]);
4791         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4792
4793         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4794         assert_eq!(spend_txn.len(), 1);
4795         assert_eq!(spend_txn[0].input.len(), 1);
4796         check_spends!(spend_txn[0], node_txn[0]);
4797         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4798 }
4799
4800 #[test]
4801 fn test_claim_on_remote_sizeable_push_msat() {
4802         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4803         // to_remote output is encumbered by a P2WPKH
4804         let chanmon_cfgs = create_chanmon_cfgs(2);
4805         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4806         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4807         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4808
4809         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4810         nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4811         check_closed_broadcast!(nodes[0], true);
4812         check_added_monitors!(nodes[0], 1);
4813         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4814
4815         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4816         assert_eq!(node_txn.len(), 1);
4817         check_spends!(node_txn[0], chan.3);
4818         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
4819
4820         mine_transaction(&nodes[1], &node_txn[0]);
4821         check_closed_broadcast!(nodes[1], true);
4822         check_added_monitors!(nodes[1], 1);
4823         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4824         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4825
4826         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4827         assert_eq!(spend_txn.len(), 1);
4828         check_spends!(spend_txn[0], node_txn[0]);
4829 }
4830
4831 #[test]
4832 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4833         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4834         // to_remote output is encumbered by a P2WPKH
4835
4836         let chanmon_cfgs = create_chanmon_cfgs(2);
4837         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4838         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4839         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4840
4841         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4842         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4843         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4844         assert_eq!(revoked_local_txn[0].input.len(), 1);
4845         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4846
4847         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4848         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4849         check_closed_broadcast!(nodes[1], true);
4850         check_added_monitors!(nodes[1], 1);
4851         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4852
4853         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4854         mine_transaction(&nodes[1], &node_txn[0]);
4855         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4856
4857         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4858         assert_eq!(spend_txn.len(), 3);
4859         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4860         check_spends!(spend_txn[1], node_txn[0]);
4861         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4862 }
4863
4864 #[test]
4865 fn test_static_spendable_outputs_preimage_tx() {
4866         let chanmon_cfgs = create_chanmon_cfgs(2);
4867         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4868         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4869         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4870
4871         // Create some initial channels
4872         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4873
4874         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4875
4876         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4877         assert_eq!(commitment_tx[0].input.len(), 1);
4878         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4879
4880         // Settle A's commitment tx on B's chain
4881         nodes[1].node.claim_funds(payment_preimage);
4882         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4883         check_added_monitors!(nodes[1], 1);
4884         mine_transaction(&nodes[1], &commitment_tx[0]);
4885         check_added_monitors!(nodes[1], 1);
4886         let events = nodes[1].node.get_and_clear_pending_msg_events();
4887         match events[0] {
4888                 MessageSendEvent::UpdateHTLCs { .. } => {},
4889                 _ => panic!("Unexpected event"),
4890         }
4891         match events[1] {
4892                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4893                 _ => panic!("Unexepected event"),
4894         }
4895
4896         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4897         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4898         assert_eq!(node_txn.len(), 3);
4899         check_spends!(node_txn[0], commitment_tx[0]);
4900         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4901         check_spends!(node_txn[1], chan_1.3);
4902         check_spends!(node_txn[2], node_txn[1]);
4903
4904         mine_transaction(&nodes[1], &node_txn[0]);
4905         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4906         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4907
4908         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4909         assert_eq!(spend_txn.len(), 1);
4910         check_spends!(spend_txn[0], node_txn[0]);
4911 }
4912
4913 #[test]
4914 fn test_static_spendable_outputs_timeout_tx() {
4915         let chanmon_cfgs = create_chanmon_cfgs(2);
4916         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4917         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4918         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4919
4920         // Create some initial channels
4921         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4922
4923         // Rebalance the network a bit by relaying one payment through all the channels ...
4924         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4925
4926         let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4927
4928         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4929         assert_eq!(commitment_tx[0].input.len(), 1);
4930         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4931
4932         // Settle A's commitment tx on B' chain
4933         mine_transaction(&nodes[1], &commitment_tx[0]);
4934         check_added_monitors!(nodes[1], 1);
4935         let events = nodes[1].node.get_and_clear_pending_msg_events();
4936         match events[0] {
4937                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4938                 _ => panic!("Unexpected event"),
4939         }
4940         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4941
4942         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4943         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4944         assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4945         check_spends!(node_txn[0], chan_1.3.clone());
4946         check_spends!(node_txn[1],  commitment_tx[0].clone());
4947         assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4948
4949         mine_transaction(&nodes[1], &node_txn[1]);
4950         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4951         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4952         expect_payment_failed!(nodes[1], our_payment_hash, true);
4953
4954         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4955         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4956         check_spends!(spend_txn[0], commitment_tx[0]);
4957         check_spends!(spend_txn[1], node_txn[1]);
4958         check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4959 }
4960
4961 #[test]
4962 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4963         let chanmon_cfgs = create_chanmon_cfgs(2);
4964         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4965         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4966         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4967
4968         // Create some initial channels
4969         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4970
4971         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4972         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4973         assert_eq!(revoked_local_txn[0].input.len(), 1);
4974         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4975
4976         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4977
4978         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4979         check_closed_broadcast!(nodes[1], true);
4980         check_added_monitors!(nodes[1], 1);
4981         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4982
4983         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4984         assert_eq!(node_txn.len(), 2);
4985         assert_eq!(node_txn[0].input.len(), 2);
4986         check_spends!(node_txn[0], revoked_local_txn[0]);
4987
4988         mine_transaction(&nodes[1], &node_txn[0]);
4989         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4990
4991         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4992         assert_eq!(spend_txn.len(), 1);
4993         check_spends!(spend_txn[0], node_txn[0]);
4994 }
4995
4996 #[test]
4997 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4998         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4999         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
5000         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5001         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5002         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5003
5004         // Create some initial channels
5005         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5006
5007         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5008         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5009         assert_eq!(revoked_local_txn[0].input.len(), 1);
5010         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5011
5012         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5013
5014         // A will generate HTLC-Timeout from revoked commitment tx
5015         mine_transaction(&nodes[0], &revoked_local_txn[0]);
5016         check_closed_broadcast!(nodes[0], true);
5017         check_added_monitors!(nodes[0], 1);
5018         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5019         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5020
5021         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
5022         assert_eq!(revoked_htlc_txn.len(), 2);
5023         check_spends!(revoked_htlc_txn[0], chan_1.3);
5024         assert_eq!(revoked_htlc_txn[1].input.len(), 1);
5025         assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5026         check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
5027         assert_ne!(revoked_htlc_txn[1].lock_time.0, 0); // HTLC-Timeout
5028
5029         // B will generate justice tx from A's revoked commitment/HTLC tx
5030         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
5031         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
5032         check_closed_broadcast!(nodes[1], true);
5033         check_added_monitors!(nodes[1], 1);
5034         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5035
5036         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5037         assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
5038         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5039         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
5040         // transactions next...
5041         assert_eq!(node_txn[0].input.len(), 3);
5042         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
5043
5044         assert_eq!(node_txn[1].input.len(), 2);
5045         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
5046         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
5047                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5048         } else {
5049                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
5050                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5051         }
5052
5053         assert_eq!(node_txn[2].input.len(), 1);
5054         check_spends!(node_txn[2], chan_1.3);
5055
5056         mine_transaction(&nodes[1], &node_txn[1]);
5057         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5058
5059         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
5060         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5061         assert_eq!(spend_txn.len(), 1);
5062         assert_eq!(spend_txn[0].input.len(), 1);
5063         check_spends!(spend_txn[0], node_txn[1]);
5064 }
5065
5066 #[test]
5067 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
5068         let mut chanmon_cfgs = create_chanmon_cfgs(2);
5069         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
5070         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5071         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5072         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5073
5074         // Create some initial channels
5075         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5076
5077         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5078         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5079         assert_eq!(revoked_local_txn[0].input.len(), 1);
5080         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5081
5082         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
5083         assert_eq!(revoked_local_txn[0].output.len(), 2);
5084
5085         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5086
5087         // B will generate HTLC-Success from revoked commitment tx
5088         mine_transaction(&nodes[1], &revoked_local_txn[0]);
5089         check_closed_broadcast!(nodes[1], true);
5090         check_added_monitors!(nodes[1], 1);
5091         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5092         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5093
5094         assert_eq!(revoked_htlc_txn.len(), 2);
5095         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5096         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5097         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5098
5099         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5100         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5101         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5102
5103         // A will generate justice tx from B's revoked commitment/HTLC tx
5104         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
5105         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
5106         check_closed_broadcast!(nodes[0], true);
5107         check_added_monitors!(nodes[0], 1);
5108         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5109
5110         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5111         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5112
5113         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5114         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5115         // transactions next...
5116         assert_eq!(node_txn[0].input.len(), 2);
5117         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5118         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5119                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5120         } else {
5121                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5122                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5123         }
5124
5125         assert_eq!(node_txn[1].input.len(), 1);
5126         check_spends!(node_txn[1], revoked_htlc_txn[0]);
5127
5128         check_spends!(node_txn[2], chan_1.3);
5129
5130         mine_transaction(&nodes[0], &node_txn[1]);
5131         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5132
5133         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5134         // didn't try to generate any new transactions.
5135
5136         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5137         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5138         assert_eq!(spend_txn.len(), 3);
5139         assert_eq!(spend_txn[0].input.len(), 1);
5140         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5141         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5142         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5143         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5144 }
5145
5146 #[test]
5147 fn test_onchain_to_onchain_claim() {
5148         // Test that in case of channel closure, we detect the state of output and claim HTLC
5149         // on downstream peer's remote commitment tx.
5150         // First, have C claim an HTLC against its own latest commitment transaction.
5151         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5152         // channel.
5153         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5154         // gets broadcast.
5155
5156         let chanmon_cfgs = create_chanmon_cfgs(3);
5157         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5158         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5159         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5160
5161         // Create some initial channels
5162         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5163         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5164
5165         // Ensure all nodes are at the same height
5166         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5167         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5168         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5169         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5170
5171         // Rebalance the network a bit by relaying one payment through all the channels ...
5172         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5173         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5174
5175         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
5176         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5177         check_spends!(commitment_tx[0], chan_2.3);
5178         nodes[2].node.claim_funds(payment_preimage);
5179         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
5180         check_added_monitors!(nodes[2], 1);
5181         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5182         assert!(updates.update_add_htlcs.is_empty());
5183         assert!(updates.update_fail_htlcs.is_empty());
5184         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5185         assert!(updates.update_fail_malformed_htlcs.is_empty());
5186
5187         mine_transaction(&nodes[2], &commitment_tx[0]);
5188         check_closed_broadcast!(nodes[2], true);
5189         check_added_monitors!(nodes[2], 1);
5190         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5191
5192         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5193         assert_eq!(c_txn.len(), 3);
5194         assert_eq!(c_txn[0], c_txn[2]);
5195         assert_eq!(commitment_tx[0], c_txn[1]);
5196         check_spends!(c_txn[1], chan_2.3);
5197         check_spends!(c_txn[2], c_txn[1]);
5198         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5199         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5200         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5201         assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
5202
5203         // 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
5204         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
5205         connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5206         check_added_monitors!(nodes[1], 1);
5207         let events = nodes[1].node.get_and_clear_pending_events();
5208         assert_eq!(events.len(), 2);
5209         match events[0] {
5210                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5211                 _ => panic!("Unexpected event"),
5212         }
5213         match events[1] {
5214                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
5215                         assert_eq!(fee_earned_msat, Some(1000));
5216                         assert_eq!(prev_channel_id, Some(chan_1.2));
5217                         assert_eq!(claim_from_onchain_tx, true);
5218                         assert_eq!(next_channel_id, Some(chan_2.2));
5219                 },
5220                 _ => panic!("Unexpected event"),
5221         }
5222         {
5223                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5224                 // ChannelMonitor: claim tx
5225                 assert_eq!(b_txn.len(), 1);
5226                 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
5227                 b_txn.clear();
5228         }
5229         check_added_monitors!(nodes[1], 1);
5230         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5231         assert_eq!(msg_events.len(), 3);
5232         match msg_events[0] {
5233                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5234                 _ => panic!("Unexpected event"),
5235         }
5236         match msg_events[1] {
5237                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5238                 _ => panic!("Unexpected event"),
5239         }
5240         match msg_events[2] {
5241                 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, .. } } => {
5242                         assert!(update_add_htlcs.is_empty());
5243                         assert!(update_fail_htlcs.is_empty());
5244                         assert_eq!(update_fulfill_htlcs.len(), 1);
5245                         assert!(update_fail_malformed_htlcs.is_empty());
5246                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5247                 },
5248                 _ => panic!("Unexpected event"),
5249         };
5250         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5251         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5252         mine_transaction(&nodes[1], &commitment_tx[0]);
5253         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5254         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5255         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5256         assert_eq!(b_txn.len(), 3);
5257         check_spends!(b_txn[1], chan_1.3);
5258         check_spends!(b_txn[2], b_txn[1]);
5259         check_spends!(b_txn[0], commitment_tx[0]);
5260         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5261         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5262         assert_eq!(b_txn[0].lock_time.0, 0); // Success tx
5263
5264         check_closed_broadcast!(nodes[1], true);
5265         check_added_monitors!(nodes[1], 1);
5266 }
5267
5268 #[test]
5269 fn test_duplicate_payment_hash_one_failure_one_success() {
5270         // Topology : A --> B --> C --> D
5271         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5272         // Note that because C will refuse to generate two payment secrets for the same payment hash,
5273         // we forward one of the payments onwards to D.
5274         let chanmon_cfgs = create_chanmon_cfgs(4);
5275         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5276         // When this test was written, the default base fee floated based on the HTLC count.
5277         // It is now fixed, so we simply set the fee to the expected value here.
5278         let mut config = test_default_channel_config();
5279         config.channel_config.forwarding_fee_base_msat = 196;
5280         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5281                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5282         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5283
5284         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5285         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5286         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5287
5288         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5289         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5290         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5291         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5292         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5293
5294         let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
5295
5296         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200).unwrap();
5297         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5298         // script push size limit so that the below script length checks match
5299         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5300         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
5301                 .with_features(InvoiceFeatures::known());
5302         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 900000, TEST_FINAL_CLTV - 40);
5303         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5304
5305         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5306         assert_eq!(commitment_txn[0].input.len(), 1);
5307         check_spends!(commitment_txn[0], chan_2.3);
5308
5309         mine_transaction(&nodes[1], &commitment_txn[0]);
5310         check_closed_broadcast!(nodes[1], true);
5311         check_added_monitors!(nodes[1], 1);
5312         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5313         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5314
5315         let htlc_timeout_tx;
5316         { // Extract one of the two HTLC-Timeout transaction
5317                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5318                 // ChannelMonitor: timeout tx * 2-or-3, ChannelManager: local commitment tx
5319                 assert!(node_txn.len() == 4 || node_txn.len() == 3);
5320                 check_spends!(node_txn[0], chan_2.3);
5321
5322                 check_spends!(node_txn[1], commitment_txn[0]);
5323                 assert_eq!(node_txn[1].input.len(), 1);
5324
5325                 if node_txn.len() > 3 {
5326                         check_spends!(node_txn[2], commitment_txn[0]);
5327                         assert_eq!(node_txn[2].input.len(), 1);
5328                         assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5329
5330                         check_spends!(node_txn[3], commitment_txn[0]);
5331                         assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5332                 } else {
5333                         check_spends!(node_txn[2], commitment_txn[0]);
5334                         assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5335                 }
5336
5337                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5338                 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5339                 if node_txn.len() > 3 {
5340                         assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5341                 }
5342                 htlc_timeout_tx = node_txn[1].clone();
5343         }
5344
5345         nodes[2].node.claim_funds(our_payment_preimage);
5346         expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
5347
5348         mine_transaction(&nodes[2], &commitment_txn[0]);
5349         check_added_monitors!(nodes[2], 2);
5350         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5351         let events = nodes[2].node.get_and_clear_pending_msg_events();
5352         match events[0] {
5353                 MessageSendEvent::UpdateHTLCs { .. } => {},
5354                 _ => panic!("Unexpected event"),
5355         }
5356         match events[1] {
5357                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5358                 _ => panic!("Unexepected event"),
5359         }
5360         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5361         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)
5362         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5363         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5364         assert_eq!(htlc_success_txn[0].input.len(), 1);
5365         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5366         assert_eq!(htlc_success_txn[1].input.len(), 1);
5367         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5368         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5369         assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5370         assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5371         assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5372         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5373
5374         mine_transaction(&nodes[1], &htlc_timeout_tx);
5375         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5376         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 }]);
5377         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5378         assert!(htlc_updates.update_add_htlcs.is_empty());
5379         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5380         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5381         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5382         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5383         check_added_monitors!(nodes[1], 1);
5384
5385         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5386         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5387         {
5388                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5389         }
5390         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5391
5392         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5393         // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5394         // and nodes[2] fee) is rounded down and then claimed in full.
5395         mine_transaction(&nodes[1], &htlc_success_txn[0]);
5396         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196*2), true, true);
5397         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5398         assert!(updates.update_add_htlcs.is_empty());
5399         assert!(updates.update_fail_htlcs.is_empty());
5400         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5401         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5402         assert!(updates.update_fail_malformed_htlcs.is_empty());
5403         check_added_monitors!(nodes[1], 1);
5404
5405         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5406         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5407
5408         let events = nodes[0].node.get_and_clear_pending_events();
5409         match events[0] {
5410                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
5411                         assert_eq!(*payment_preimage, our_payment_preimage);
5412                         assert_eq!(*payment_hash, duplicate_payment_hash);
5413                 }
5414                 _ => panic!("Unexpected event"),
5415         }
5416 }
5417
5418 #[test]
5419 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5420         let chanmon_cfgs = create_chanmon_cfgs(2);
5421         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5422         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5423         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5424
5425         // Create some initial channels
5426         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5427
5428         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
5429         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5430         assert_eq!(local_txn.len(), 1);
5431         assert_eq!(local_txn[0].input.len(), 1);
5432         check_spends!(local_txn[0], chan_1.3);
5433
5434         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5435         nodes[1].node.claim_funds(payment_preimage);
5436         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
5437         check_added_monitors!(nodes[1], 1);
5438
5439         mine_transaction(&nodes[1], &local_txn[0]);
5440         check_added_monitors!(nodes[1], 1);
5441         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5442         let events = nodes[1].node.get_and_clear_pending_msg_events();
5443         match events[0] {
5444                 MessageSendEvent::UpdateHTLCs { .. } => {},
5445                 _ => panic!("Unexpected event"),
5446         }
5447         match events[1] {
5448                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5449                 _ => panic!("Unexepected event"),
5450         }
5451         let node_tx = {
5452                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5453                 assert_eq!(node_txn.len(), 3);
5454                 assert_eq!(node_txn[0], node_txn[2]);
5455                 assert_eq!(node_txn[1], local_txn[0]);
5456                 assert_eq!(node_txn[0].input.len(), 1);
5457                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5458                 check_spends!(node_txn[0], local_txn[0]);
5459                 node_txn[0].clone()
5460         };
5461
5462         mine_transaction(&nodes[1], &node_tx);
5463         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5464
5465         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5466         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5467         assert_eq!(spend_txn.len(), 1);
5468         assert_eq!(spend_txn[0].input.len(), 1);
5469         check_spends!(spend_txn[0], node_tx);
5470         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5471 }
5472
5473 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5474         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5475         // unrevoked commitment transaction.
5476         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5477         // a remote RAA before they could be failed backwards (and combinations thereof).
5478         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5479         // use the same payment hashes.
5480         // Thus, we use a six-node network:
5481         //
5482         // A \         / E
5483         //    - C - D -
5484         // B /         \ F
5485         // And test where C fails back to A/B when D announces its latest commitment transaction
5486         let chanmon_cfgs = create_chanmon_cfgs(6);
5487         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5488         // When this test was written, the default base fee floated based on the HTLC count.
5489         // It is now fixed, so we simply set the fee to the expected value here.
5490         let mut config = test_default_channel_config();
5491         config.channel_config.forwarding_fee_base_msat = 196;
5492         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5493                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5494         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5495
5496         let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5497         let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5498         let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5499         let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5500         let chan_3_5  = create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5501
5502         // Rebalance and check output sanity...
5503         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5504         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5505         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
5506
5507         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan_2_3.2).unwrap().holder_dust_limit_satoshis;
5508         // 0th HTLC:
5509         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
5510         // 1st HTLC:
5511         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
5512         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5513         // 2nd HTLC:
5514         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
5515         // 3rd HTLC:
5516         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
5517         // 4th HTLC:
5518         let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5519         // 5th HTLC:
5520         let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5521         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5522         // 6th HTLC:
5523         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());
5524         // 7th HTLC:
5525         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());
5526
5527         // 8th HTLC:
5528         let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5529         // 9th HTLC:
5530         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5531         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
5532
5533         // 10th HTLC:
5534         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
5535         // 11th HTLC:
5536         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5537         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());
5538
5539         // Double-check that six of the new HTLC were added
5540         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5541         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5542         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5543         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5544
5545         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5546         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5547         nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5548         nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5549         nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5550         nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5551         check_added_monitors!(nodes[4], 0);
5552
5553         let failed_destinations = vec![
5554                 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5555                 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5556                 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5557                 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5558         ];
5559         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5560         check_added_monitors!(nodes[4], 1);
5561
5562         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5563         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5564         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5565         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5566         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5567         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5568
5569         // Fail 3rd below-dust and 7th above-dust HTLCs
5570         nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5571         nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5572         check_added_monitors!(nodes[5], 0);
5573
5574         let failed_destinations_2 = vec![
5575                 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5576                 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5577         ];
5578         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5579         check_added_monitors!(nodes[5], 1);
5580
5581         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5582         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5583         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5584         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5585
5586         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5587
5588         // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5589         let failed_destinations_3 = vec![
5590                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5591                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5592                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5593                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5594                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5595                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5596         ];
5597         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5598         check_added_monitors!(nodes[3], 1);
5599         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5600         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5601         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5602         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5603         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5604         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5605         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5606         if deliver_last_raa {
5607                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5608         } else {
5609                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5610         }
5611
5612         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5613         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5614         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5615         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5616         //
5617         // We now broadcast the latest commitment transaction, which *should* result in failures for
5618         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5619         // the non-broadcast above-dust HTLCs.
5620         //
5621         // Alternatively, we may broadcast the previous commitment transaction, which should only
5622         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5623         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5624
5625         if announce_latest {
5626                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5627         } else {
5628                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5629         }
5630         let events = nodes[2].node.get_and_clear_pending_events();
5631         let close_event = if deliver_last_raa {
5632                 assert_eq!(events.len(), 2 + 6);
5633                 events.last().clone().unwrap()
5634         } else {
5635                 assert_eq!(events.len(), 1);
5636                 events.last().clone().unwrap()
5637         };
5638         match close_event {
5639                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5640                 _ => panic!("Unexpected event"),
5641         }
5642
5643         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5644         check_closed_broadcast!(nodes[2], true);
5645         if deliver_last_raa {
5646                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5647
5648                 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();
5649                 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5650         } else {
5651                 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5652                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5653                 } else {
5654                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5655                 };
5656
5657                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5658         }
5659         check_added_monitors!(nodes[2], 3);
5660
5661         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5662         assert_eq!(cs_msgs.len(), 2);
5663         let mut a_done = false;
5664         for msg in cs_msgs {
5665                 match msg {
5666                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5667                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5668                                 // should be failed-backwards here.
5669                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5670                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5671                                         for htlc in &updates.update_fail_htlcs {
5672                                                 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 });
5673                                         }
5674                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5675                                         assert!(!a_done);
5676                                         a_done = true;
5677                                         &nodes[0]
5678                                 } else {
5679                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5680                                         for htlc in &updates.update_fail_htlcs {
5681                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5682                                         }
5683                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5684                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5685                                         &nodes[1]
5686                                 };
5687                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5688                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5689                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5690                                 if announce_latest {
5691                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5692                                         if *node_id == nodes[0].node.get_our_node_id() {
5693                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5694                                         }
5695                                 }
5696                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5697                         },
5698                         _ => panic!("Unexpected event"),
5699                 }
5700         }
5701
5702         let as_events = nodes[0].node.get_and_clear_pending_events();
5703         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5704         let mut as_failds = HashSet::new();
5705         let mut as_updates = 0;
5706         for event in as_events.iter() {
5707                 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5708                         assert!(as_failds.insert(*payment_hash));
5709                         if *payment_hash != payment_hash_2 {
5710                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5711                         } else {
5712                                 assert!(!rejected_by_dest);
5713                         }
5714                         if network_update.is_some() {
5715                                 as_updates += 1;
5716                         }
5717                 } else { panic!("Unexpected event"); }
5718         }
5719         assert!(as_failds.contains(&payment_hash_1));
5720         assert!(as_failds.contains(&payment_hash_2));
5721         if announce_latest {
5722                 assert!(as_failds.contains(&payment_hash_3));
5723                 assert!(as_failds.contains(&payment_hash_5));
5724         }
5725         assert!(as_failds.contains(&payment_hash_6));
5726
5727         let bs_events = nodes[1].node.get_and_clear_pending_events();
5728         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5729         let mut bs_failds = HashSet::new();
5730         let mut bs_updates = 0;
5731         for event in bs_events.iter() {
5732                 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5733                         assert!(bs_failds.insert(*payment_hash));
5734                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5735                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5736                         } else {
5737                                 assert!(!rejected_by_dest);
5738                         }
5739                         if network_update.is_some() {
5740                                 bs_updates += 1;
5741                         }
5742                 } else { panic!("Unexpected event"); }
5743         }
5744         assert!(bs_failds.contains(&payment_hash_1));
5745         assert!(bs_failds.contains(&payment_hash_2));
5746         if announce_latest {
5747                 assert!(bs_failds.contains(&payment_hash_4));
5748         }
5749         assert!(bs_failds.contains(&payment_hash_5));
5750
5751         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5752         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5753         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5754         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5755         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5756         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5757 }
5758
5759 #[test]
5760 fn test_fail_backwards_latest_remote_announce_a() {
5761         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5762 }
5763
5764 #[test]
5765 fn test_fail_backwards_latest_remote_announce_b() {
5766         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5767 }
5768
5769 #[test]
5770 fn test_fail_backwards_previous_remote_announce() {
5771         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5772         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5773         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5774 }
5775
5776 #[test]
5777 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5778         let chanmon_cfgs = create_chanmon_cfgs(2);
5779         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5780         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5781         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5782
5783         // Create some initial channels
5784         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5785
5786         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5787         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5788         assert_eq!(local_txn[0].input.len(), 1);
5789         check_spends!(local_txn[0], chan_1.3);
5790
5791         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5792         mine_transaction(&nodes[0], &local_txn[0]);
5793         check_closed_broadcast!(nodes[0], true);
5794         check_added_monitors!(nodes[0], 1);
5795         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5796         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5797
5798         let htlc_timeout = {
5799                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5800                 assert_eq!(node_txn.len(), 2);
5801                 check_spends!(node_txn[0], chan_1.3);
5802                 assert_eq!(node_txn[1].input.len(), 1);
5803                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5804                 check_spends!(node_txn[1], local_txn[0]);
5805                 node_txn[1].clone()
5806         };
5807
5808         mine_transaction(&nodes[0], &htlc_timeout);
5809         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5810         expect_payment_failed!(nodes[0], our_payment_hash, true);
5811
5812         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5813         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5814         assert_eq!(spend_txn.len(), 3);
5815         check_spends!(spend_txn[0], local_txn[0]);
5816         assert_eq!(spend_txn[1].input.len(), 1);
5817         check_spends!(spend_txn[1], htlc_timeout);
5818         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5819         assert_eq!(spend_txn[2].input.len(), 2);
5820         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5821         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5822                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5823 }
5824
5825 #[test]
5826 fn test_key_derivation_params() {
5827         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5828         // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5829         // let us re-derive the channel key set to then derive a delayed_payment_key.
5830
5831         let chanmon_cfgs = create_chanmon_cfgs(3);
5832
5833         // We manually create the node configuration to backup the seed.
5834         let seed = [42; 32];
5835         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5836         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);
5837         let network_graph = NetworkGraph::new(chanmon_cfgs[0].chain_source.genesis_hash, &chanmon_cfgs[0].logger);
5838         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() };
5839         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5840         node_cfgs.remove(0);
5841         node_cfgs.insert(0, node);
5842
5843         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5844         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5845
5846         // Create some initial channels
5847         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5848         // for node 0
5849         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5850         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5851         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5852
5853         // Ensure all nodes are at the same height
5854         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5855         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5856         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5857         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5858
5859         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5860         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5861         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5862         assert_eq!(local_txn_1[0].input.len(), 1);
5863         check_spends!(local_txn_1[0], chan_1.3);
5864
5865         // We check funding pubkey are unique
5866         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]));
5867         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]));
5868         if from_0_funding_key_0 == from_1_funding_key_0
5869             || from_0_funding_key_0 == from_1_funding_key_1
5870             || from_0_funding_key_1 == from_1_funding_key_0
5871             || from_0_funding_key_1 == from_1_funding_key_1 {
5872                 panic!("Funding pubkeys aren't unique");
5873         }
5874
5875         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5876         mine_transaction(&nodes[0], &local_txn_1[0]);
5877         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5878         check_closed_broadcast!(nodes[0], true);
5879         check_added_monitors!(nodes[0], 1);
5880         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5881
5882         let htlc_timeout = {
5883                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5884                 assert_eq!(node_txn[1].input.len(), 1);
5885                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5886                 check_spends!(node_txn[1], local_txn_1[0]);
5887                 node_txn[1].clone()
5888         };
5889
5890         mine_transaction(&nodes[0], &htlc_timeout);
5891         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5892         expect_payment_failed!(nodes[0], our_payment_hash, true);
5893
5894         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5895         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5896         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5897         assert_eq!(spend_txn.len(), 3);
5898         check_spends!(spend_txn[0], local_txn_1[0]);
5899         assert_eq!(spend_txn[1].input.len(), 1);
5900         check_spends!(spend_txn[1], htlc_timeout);
5901         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5902         assert_eq!(spend_txn[2].input.len(), 2);
5903         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5904         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5905                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5906 }
5907
5908 #[test]
5909 fn test_static_output_closing_tx() {
5910         let chanmon_cfgs = create_chanmon_cfgs(2);
5911         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5912         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5913         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5914
5915         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5916
5917         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5918         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5919
5920         mine_transaction(&nodes[0], &closing_tx);
5921         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5922         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5923
5924         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5925         assert_eq!(spend_txn.len(), 1);
5926         check_spends!(spend_txn[0], closing_tx);
5927
5928         mine_transaction(&nodes[1], &closing_tx);
5929         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5930         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5931
5932         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5933         assert_eq!(spend_txn.len(), 1);
5934         check_spends!(spend_txn[0], closing_tx);
5935 }
5936
5937 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5938         let chanmon_cfgs = create_chanmon_cfgs(2);
5939         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5940         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5941         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5942         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5943
5944         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5945
5946         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5947         // present in B's local commitment transaction, but none of A's commitment transactions.
5948         nodes[1].node.claim_funds(payment_preimage);
5949         check_added_monitors!(nodes[1], 1);
5950         expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5951
5952         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5953         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5954         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5955
5956         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5957         check_added_monitors!(nodes[0], 1);
5958         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5959         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5960         check_added_monitors!(nodes[1], 1);
5961
5962         let starting_block = nodes[1].best_block_info();
5963         let mut block = Block {
5964                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
5965                 txdata: vec![],
5966         };
5967         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5968                 connect_block(&nodes[1], &block);
5969                 block.header.prev_blockhash = block.block_hash();
5970         }
5971         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5972         check_closed_broadcast!(nodes[1], true);
5973         check_added_monitors!(nodes[1], 1);
5974         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5975 }
5976
5977 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5978         let chanmon_cfgs = create_chanmon_cfgs(2);
5979         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5980         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5981         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5982         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5983
5984         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5985         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5986         check_added_monitors!(nodes[0], 1);
5987
5988         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5989
5990         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5991         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5992         // to "time out" the HTLC.
5993
5994         let starting_block = nodes[1].best_block_info();
5995         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
5996
5997         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5998                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5999                 header.prev_blockhash = header.block_hash();
6000         }
6001         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
6002         check_closed_broadcast!(nodes[0], true);
6003         check_added_monitors!(nodes[0], 1);
6004         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6005 }
6006
6007 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
6008         let chanmon_cfgs = create_chanmon_cfgs(3);
6009         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6010         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6011         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6012         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6013
6014         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
6015         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
6016         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
6017         // actually revoked.
6018         let htlc_value = if use_dust { 50000 } else { 3000000 };
6019         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
6020         nodes[1].node.fail_htlc_backwards(&our_payment_hash);
6021         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
6022         check_added_monitors!(nodes[1], 1);
6023
6024         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6025         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
6026         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
6027         check_added_monitors!(nodes[0], 1);
6028         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6029         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
6030         check_added_monitors!(nodes[1], 1);
6031         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
6032         check_added_monitors!(nodes[1], 1);
6033         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6034
6035         if check_revoke_no_close {
6036                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
6037                 check_added_monitors!(nodes[0], 1);
6038         }
6039
6040         let starting_block = nodes[1].best_block_info();
6041         let mut block = Block {
6042                 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
6043                 txdata: vec![],
6044         };
6045         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
6046                 connect_block(&nodes[0], &block);
6047                 block.header.prev_blockhash = block.block_hash();
6048         }
6049         if !check_revoke_no_close {
6050                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
6051                 check_closed_broadcast!(nodes[0], true);
6052                 check_added_monitors!(nodes[0], 1);
6053                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6054         } else {
6055                 let events = nodes[0].node.get_and_clear_pending_events();
6056                 assert_eq!(events.len(), 2);
6057                 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
6058                         assert_eq!(*payment_hash, our_payment_hash);
6059                 } else { panic!("Unexpected event"); }
6060                 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
6061                         assert_eq!(*payment_hash, our_payment_hash);
6062                 } else { panic!("Unexpected event"); }
6063         }
6064 }
6065
6066 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
6067 // There are only a few cases to test here:
6068 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
6069 //    broadcastable commitment transactions result in channel closure,
6070 //  * its included in an unrevoked-but-previous remote commitment transaction,
6071 //  * its included in the latest remote or local commitment transactions.
6072 // We test each of the three possible commitment transactions individually and use both dust and
6073 // non-dust HTLCs.
6074 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
6075 // assume they are handled the same across all six cases, as both outbound and inbound failures are
6076 // tested for at least one of the cases in other tests.
6077 #[test]
6078 fn htlc_claim_single_commitment_only_a() {
6079         do_htlc_claim_local_commitment_only(true);
6080         do_htlc_claim_local_commitment_only(false);
6081
6082         do_htlc_claim_current_remote_commitment_only(true);
6083         do_htlc_claim_current_remote_commitment_only(false);
6084 }
6085
6086 #[test]
6087 fn htlc_claim_single_commitment_only_b() {
6088         do_htlc_claim_previous_remote_commitment_only(true, false);
6089         do_htlc_claim_previous_remote_commitment_only(false, false);
6090         do_htlc_claim_previous_remote_commitment_only(true, true);
6091         do_htlc_claim_previous_remote_commitment_only(false, true);
6092 }
6093
6094 #[test]
6095 #[should_panic]
6096 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
6097         let chanmon_cfgs = create_chanmon_cfgs(2);
6098         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6099         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6100         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6101         // Force duplicate randomness for every get-random call
6102         for node in nodes.iter() {
6103                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
6104         }
6105
6106         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
6107         let channel_value_satoshis=10000;
6108         let push_msat=10001;
6109         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6110         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6111         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6112         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6113
6114         // Create a second channel with the same random values. This used to panic due to a colliding
6115         // channel_id, but now panics due to a colliding outbound SCID alias.
6116         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6117 }
6118
6119 #[test]
6120 fn bolt2_open_channel_sending_node_checks_part2() {
6121         let chanmon_cfgs = create_chanmon_cfgs(2);
6122         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6123         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6124         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6125
6126         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
6127         let channel_value_satoshis=2^24;
6128         let push_msat=10001;
6129         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6130
6131         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
6132         let channel_value_satoshis=10000;
6133         // Test when push_msat is equal to 1000 * funding_satoshis.
6134         let push_msat=1000*channel_value_satoshis+1;
6135         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6136
6137         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
6138         let channel_value_satoshis=10000;
6139         let push_msat=10001;
6140         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
6141         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6142         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
6143
6144         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
6145         // 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
6146         assert!(node0_to_1_send_open_channel.channel_flags<=1);
6147
6148         // 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.
6149         assert!(BREAKDOWN_TIMEOUT>0);
6150         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
6151
6152         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
6153         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
6154         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
6155
6156         // 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.
6157         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
6158         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
6159         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
6160         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
6161         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6162 }
6163
6164 #[test]
6165 fn bolt2_open_channel_sane_dust_limit() {
6166         let chanmon_cfgs = create_chanmon_cfgs(2);
6167         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6168         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6169         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6170
6171         let channel_value_satoshis=1000000;
6172         let push_msat=10001;
6173         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6174         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6175         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
6176         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
6177
6178         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6179         let events = nodes[1].node.get_and_clear_pending_msg_events();
6180         let err_msg = match events[0] {
6181                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
6182                         msg.clone()
6183                 },
6184                 _ => panic!("Unexpected event"),
6185         };
6186         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
6187 }
6188
6189 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6190 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6191 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6192 // is no longer affordable once it's freed.
6193 #[test]
6194 fn test_fail_holding_cell_htlc_upon_free() {
6195         let chanmon_cfgs = create_chanmon_cfgs(2);
6196         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6197         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6198         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6199         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6200
6201         // First nodes[0] generates an update_fee, setting the channel's
6202         // pending_update_fee.
6203         {
6204                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6205                 *feerate_lock += 20;
6206         }
6207         nodes[0].node.timer_tick_occurred();
6208         check_added_monitors!(nodes[0], 1);
6209
6210         let events = nodes[0].node.get_and_clear_pending_msg_events();
6211         assert_eq!(events.len(), 1);
6212         let (update_msg, commitment_signed) = match events[0] {
6213                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6214                         (update_fee.as_ref(), commitment_signed)
6215                 },
6216                 _ => panic!("Unexpected event"),
6217         };
6218
6219         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6220
6221         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6222         let channel_reserve = chan_stat.channel_reserve_msat;
6223         let feerate = get_feerate!(nodes[0], chan.2);
6224         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6225
6226         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6227         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6228         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6229
6230         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6231         let our_payment_id = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6232         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6233         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6234
6235         // Flush the pending fee update.
6236         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6237         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6238         check_added_monitors!(nodes[1], 1);
6239         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6240         check_added_monitors!(nodes[0], 1);
6241
6242         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6243         // HTLC, but now that the fee has been raised the payment will now fail, causing
6244         // us to surface its failure to the user.
6245         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6246         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6247         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);
6248         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 {}",
6249                 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6250         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6251
6252         // Check that the payment failed to be sent out.
6253         let events = nodes[0].node.get_and_clear_pending_events();
6254         assert_eq!(events.len(), 1);
6255         match &events[0] {
6256                 &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, .. } => {
6257                         assert_eq!(our_payment_id, *payment_id.as_ref().unwrap());
6258                         assert_eq!(our_payment_hash.clone(), *payment_hash);
6259                         assert_eq!(*rejected_by_dest, false);
6260                         assert_eq!(*all_paths_failed, true);
6261                         assert_eq!(*network_update, None);
6262                         assert_eq!(*short_channel_id, None);
6263                         assert_eq!(*error_code, None);
6264                         assert_eq!(*error_data, None);
6265                 },
6266                 _ => panic!("Unexpected event"),
6267         }
6268 }
6269
6270 // Test that if multiple HTLCs are released from the holding cell and one is
6271 // valid but the other is no longer valid upon release, the valid HTLC can be
6272 // successfully completed while the other one fails as expected.
6273 #[test]
6274 fn test_free_and_fail_holding_cell_htlcs() {
6275         let chanmon_cfgs = create_chanmon_cfgs(2);
6276         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6277         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6278         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6279         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6280
6281         // First nodes[0] generates an update_fee, setting the channel's
6282         // pending_update_fee.
6283         {
6284                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6285                 *feerate_lock += 200;
6286         }
6287         nodes[0].node.timer_tick_occurred();
6288         check_added_monitors!(nodes[0], 1);
6289
6290         let events = nodes[0].node.get_and_clear_pending_msg_events();
6291         assert_eq!(events.len(), 1);
6292         let (update_msg, commitment_signed) = match events[0] {
6293                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6294                         (update_fee.as_ref(), commitment_signed)
6295                 },
6296                 _ => panic!("Unexpected event"),
6297         };
6298
6299         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6300
6301         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6302         let channel_reserve = chan_stat.channel_reserve_msat;
6303         let feerate = get_feerate!(nodes[0], chan.2);
6304         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6305
6306         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6307         let amt_1 = 20000;
6308         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
6309         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6310         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6311
6312         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6313         nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
6314         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6315         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6316         let payment_id_2 = nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6317         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6318         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6319
6320         // Flush the pending fee update.
6321         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6322         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6323         check_added_monitors!(nodes[1], 1);
6324         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6325         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6326         check_added_monitors!(nodes[0], 2);
6327
6328         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6329         // but now that the fee has been raised the second payment will now fail, causing us
6330         // to surface its failure to the user. The first payment should succeed.
6331         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6332         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6333         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);
6334         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 {}",
6335                 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6336         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6337
6338         // Check that the second payment failed to be sent out.
6339         let events = nodes[0].node.get_and_clear_pending_events();
6340         assert_eq!(events.len(), 1);
6341         match &events[0] {
6342                 &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, .. } => {
6343                         assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6344                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6345                         assert_eq!(*rejected_by_dest, false);
6346                         assert_eq!(*all_paths_failed, true);
6347                         assert_eq!(*network_update, None);
6348                         assert_eq!(*short_channel_id, None);
6349                         assert_eq!(*error_code, None);
6350                         assert_eq!(*error_data, None);
6351                 },
6352                 _ => panic!("Unexpected event"),
6353         }
6354
6355         // Complete the first payment and the RAA from the fee update.
6356         let (payment_event, send_raa_event) = {
6357                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6358                 assert_eq!(msgs.len(), 2);
6359                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6360         };
6361         let raa = match send_raa_event {
6362                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6363                 _ => panic!("Unexpected event"),
6364         };
6365         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6366         check_added_monitors!(nodes[1], 1);
6367         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6368         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6369         let events = nodes[1].node.get_and_clear_pending_events();
6370         assert_eq!(events.len(), 1);
6371         match events[0] {
6372                 Event::PendingHTLCsForwardable { .. } => {},
6373                 _ => panic!("Unexpected event"),
6374         }
6375         nodes[1].node.process_pending_htlc_forwards();
6376         let events = nodes[1].node.get_and_clear_pending_events();
6377         assert_eq!(events.len(), 1);
6378         match events[0] {
6379                 Event::PaymentReceived { .. } => {},
6380                 _ => panic!("Unexpected event"),
6381         }
6382         nodes[1].node.claim_funds(payment_preimage_1);
6383         check_added_monitors!(nodes[1], 1);
6384         expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
6385
6386         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6387         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6388         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6389         expect_payment_sent!(nodes[0], payment_preimage_1);
6390 }
6391
6392 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6393 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6394 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6395 // once it's freed.
6396 #[test]
6397 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6398         let chanmon_cfgs = create_chanmon_cfgs(3);
6399         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6400         // When this test was written, the default base fee floated based on the HTLC count.
6401         // It is now fixed, so we simply set the fee to the expected value here.
6402         let mut config = test_default_channel_config();
6403         config.channel_config.forwarding_fee_base_msat = 196;
6404         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6405         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6406         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6407         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6408
6409         // First nodes[1] generates an update_fee, setting the channel's
6410         // pending_update_fee.
6411         {
6412                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6413                 *feerate_lock += 20;
6414         }
6415         nodes[1].node.timer_tick_occurred();
6416         check_added_monitors!(nodes[1], 1);
6417
6418         let events = nodes[1].node.get_and_clear_pending_msg_events();
6419         assert_eq!(events.len(), 1);
6420         let (update_msg, commitment_signed) = match events[0] {
6421                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6422                         (update_fee.as_ref(), commitment_signed)
6423                 },
6424                 _ => panic!("Unexpected event"),
6425         };
6426
6427         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6428
6429         let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6430         let channel_reserve = chan_stat.channel_reserve_msat;
6431         let feerate = get_feerate!(nodes[0], chan_0_1.2);
6432         let opt_anchors = get_opt_anchors!(nodes[0], chan_0_1.2);
6433
6434         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6435         let feemsat = 239;
6436         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6437         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
6438         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6439         let payment_event = {
6440                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6441                 check_added_monitors!(nodes[0], 1);
6442
6443                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6444                 assert_eq!(events.len(), 1);
6445
6446                 SendEvent::from_event(events.remove(0))
6447         };
6448         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6449         check_added_monitors!(nodes[1], 0);
6450         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6451         expect_pending_htlcs_forwardable!(nodes[1]);
6452
6453         chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6454         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6455
6456         // Flush the pending fee update.
6457         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6458         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6459         check_added_monitors!(nodes[2], 1);
6460         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6461         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6462         check_added_monitors!(nodes[1], 2);
6463
6464         // A final RAA message is generated to finalize the fee update.
6465         let events = nodes[1].node.get_and_clear_pending_msg_events();
6466         assert_eq!(events.len(), 1);
6467
6468         let raa_msg = match &events[0] {
6469                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6470                         msg.clone()
6471                 },
6472                 _ => panic!("Unexpected event"),
6473         };
6474
6475         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6476         check_added_monitors!(nodes[2], 1);
6477         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6478
6479         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6480         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6481         assert_eq!(process_htlc_forwards_event.len(), 2);
6482         match &process_htlc_forwards_event[0] {
6483                 &Event::PendingHTLCsForwardable { .. } => {},
6484                 _ => panic!("Unexpected event"),
6485         }
6486
6487         // In response, we call ChannelManager's process_pending_htlc_forwards
6488         nodes[1].node.process_pending_htlc_forwards();
6489         check_added_monitors!(nodes[1], 1);
6490
6491         // This causes the HTLC to be failed backwards.
6492         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6493         assert_eq!(fail_event.len(), 1);
6494         let (fail_msg, commitment_signed) = match &fail_event[0] {
6495                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6496                         assert_eq!(updates.update_add_htlcs.len(), 0);
6497                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6498                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6499                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6500                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6501                 },
6502                 _ => panic!("Unexpected event"),
6503         };
6504
6505         // Pass the failure messages back to nodes[0].
6506         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6507         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6508
6509         // Complete the HTLC failure+removal process.
6510         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6511         check_added_monitors!(nodes[0], 1);
6512         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6513         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6514         check_added_monitors!(nodes[1], 2);
6515         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6516         assert_eq!(final_raa_event.len(), 1);
6517         let raa = match &final_raa_event[0] {
6518                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6519                 _ => panic!("Unexpected event"),
6520         };
6521         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6522         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6523         check_added_monitors!(nodes[0], 1);
6524 }
6525
6526 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6527 // 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.
6528 //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.
6529
6530 #[test]
6531 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6532         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6533         let chanmon_cfgs = create_chanmon_cfgs(2);
6534         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6535         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6536         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6537         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6538
6539         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6540         route.paths[0][0].fee_msat = 100;
6541
6542         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6543                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6544         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6545         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6546 }
6547
6548 #[test]
6549 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6550         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6551         let chanmon_cfgs = create_chanmon_cfgs(2);
6552         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6553         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6554         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6555         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6556
6557         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6558         route.paths[0][0].fee_msat = 0;
6559         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6560                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6561
6562         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6563         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6564 }
6565
6566 #[test]
6567 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6568         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6569         let chanmon_cfgs = create_chanmon_cfgs(2);
6570         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6571         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6572         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6573         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6574
6575         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6576         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6577         check_added_monitors!(nodes[0], 1);
6578         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6579         updates.update_add_htlcs[0].amount_msat = 0;
6580
6581         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6582         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6583         check_closed_broadcast!(nodes[1], true).unwrap();
6584         check_added_monitors!(nodes[1], 1);
6585         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6586 }
6587
6588 #[test]
6589 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6590         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6591         //It is enforced when constructing a route.
6592         let chanmon_cfgs = create_chanmon_cfgs(2);
6593         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6594         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6595         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6596         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6597
6598         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
6599                 .with_features(InvoiceFeatures::known());
6600         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
6601         route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6602         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6603                 assert_eq!(err, &"Channel CLTV overflowed?"));
6604 }
6605
6606 #[test]
6607 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6608         //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.
6609         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6610         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6611         let chanmon_cfgs = create_chanmon_cfgs(2);
6612         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6613         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6614         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6615         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6616         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6617
6618         for i in 0..max_accepted_htlcs {
6619                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6620                 let payment_event = {
6621                         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6622                         check_added_monitors!(nodes[0], 1);
6623
6624                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6625                         assert_eq!(events.len(), 1);
6626                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6627                                 assert_eq!(htlcs[0].htlc_id, i);
6628                         } else {
6629                                 assert!(false);
6630                         }
6631                         SendEvent::from_event(events.remove(0))
6632                 };
6633                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6634                 check_added_monitors!(nodes[1], 0);
6635                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6636
6637                 expect_pending_htlcs_forwardable!(nodes[1]);
6638                 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6639         }
6640         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6641         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6642                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6643
6644         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6645         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6646 }
6647
6648 #[test]
6649 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6650         //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.
6651         let chanmon_cfgs = create_chanmon_cfgs(2);
6652         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6653         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6654         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6655         let channel_value = 100000;
6656         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6657         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6658
6659         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6660
6661         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6662         // Manually create a route over our max in flight (which our router normally automatically
6663         // limits us to.
6664         route.paths[0][0].fee_msat =  max_in_flight + 1;
6665         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6666                 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)));
6667
6668         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6669         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);
6670
6671         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6672 }
6673
6674 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6675 #[test]
6676 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6677         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6678         let chanmon_cfgs = create_chanmon_cfgs(2);
6679         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6680         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6681         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6682         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6683         let htlc_minimum_msat: u64;
6684         {
6685                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6686                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6687                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6688         }
6689
6690         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6691         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6692         check_added_monitors!(nodes[0], 1);
6693         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6694         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6695         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6696         assert!(nodes[1].node.list_channels().is_empty());
6697         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6698         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()));
6699         check_added_monitors!(nodes[1], 1);
6700         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6701 }
6702
6703 #[test]
6704 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6705         //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
6706         let chanmon_cfgs = create_chanmon_cfgs(2);
6707         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6708         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6709         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6710         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6711
6712         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6713         let channel_reserve = chan_stat.channel_reserve_msat;
6714         let feerate = get_feerate!(nodes[0], chan.2);
6715         let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6716         // The 2* and +1 are for the fee spike reserve.
6717         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6718
6719         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6720         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6721         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6722         check_added_monitors!(nodes[0], 1);
6723         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6724
6725         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6726         // at this time channel-initiatee receivers are not required to enforce that senders
6727         // respect the fee_spike_reserve.
6728         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6729         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6730
6731         assert!(nodes[1].node.list_channels().is_empty());
6732         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6733         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6734         check_added_monitors!(nodes[1], 1);
6735         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6736 }
6737
6738 #[test]
6739 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6740         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6741         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6742         let chanmon_cfgs = create_chanmon_cfgs(2);
6743         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6744         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6745         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6746         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6747
6748         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6749         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6750         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6751         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6752         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6753         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6754
6755         let mut msg = msgs::UpdateAddHTLC {
6756                 channel_id: chan.2,
6757                 htlc_id: 0,
6758                 amount_msat: 1000,
6759                 payment_hash: our_payment_hash,
6760                 cltv_expiry: htlc_cltv,
6761                 onion_routing_packet: onion_packet.clone(),
6762         };
6763
6764         for i in 0..super::channel::OUR_MAX_HTLCS {
6765                 msg.htlc_id = i as u64;
6766                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6767         }
6768         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6769         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6770
6771         assert!(nodes[1].node.list_channels().is_empty());
6772         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6773         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6774         check_added_monitors!(nodes[1], 1);
6775         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6776 }
6777
6778 #[test]
6779 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6780         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6781         let chanmon_cfgs = create_chanmon_cfgs(2);
6782         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6783         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6784         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6785         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6786
6787         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6788         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6789         check_added_monitors!(nodes[0], 1);
6790         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6791         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6792         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6793
6794         assert!(nodes[1].node.list_channels().is_empty());
6795         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6796         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6797         check_added_monitors!(nodes[1], 1);
6798         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6799 }
6800
6801 #[test]
6802 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6803         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6804         let chanmon_cfgs = create_chanmon_cfgs(2);
6805         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6806         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6807         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6808
6809         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6810         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6811         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6812         check_added_monitors!(nodes[0], 1);
6813         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6814         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6815         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6816
6817         assert!(nodes[1].node.list_channels().is_empty());
6818         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6819         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6820         check_added_monitors!(nodes[1], 1);
6821         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6822 }
6823
6824 #[test]
6825 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6826         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6827         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6828         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6829         let chanmon_cfgs = create_chanmon_cfgs(2);
6830         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6831         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6832         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6833
6834         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6835         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6836         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6837         check_added_monitors!(nodes[0], 1);
6838         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6839         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6840
6841         //Disconnect and Reconnect
6842         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6843         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6844         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6845         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6846         assert_eq!(reestablish_1.len(), 1);
6847         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6848         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6849         assert_eq!(reestablish_2.len(), 1);
6850         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6851         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6852         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6853         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6854
6855         //Resend HTLC
6856         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6857         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6858         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6859         check_added_monitors!(nodes[1], 1);
6860         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6861
6862         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6863
6864         assert!(nodes[1].node.list_channels().is_empty());
6865         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6866         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6867         check_added_monitors!(nodes[1], 1);
6868         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6869 }
6870
6871 #[test]
6872 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6873         //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.
6874
6875         let chanmon_cfgs = create_chanmon_cfgs(2);
6876         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6877         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6878         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6879         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6880         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6881         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6882
6883         check_added_monitors!(nodes[0], 1);
6884         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6885         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6886
6887         let update_msg = msgs::UpdateFulfillHTLC{
6888                 channel_id: chan.2,
6889                 htlc_id: 0,
6890                 payment_preimage: our_payment_preimage,
6891         };
6892
6893         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6894
6895         assert!(nodes[0].node.list_channels().is_empty());
6896         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6897         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()));
6898         check_added_monitors!(nodes[0], 1);
6899         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6900 }
6901
6902 #[test]
6903 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6904         //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.
6905
6906         let chanmon_cfgs = create_chanmon_cfgs(2);
6907         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6908         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6909         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6910         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6911
6912         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6913         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6914         check_added_monitors!(nodes[0], 1);
6915         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6916         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6917
6918         let update_msg = msgs::UpdateFailHTLC{
6919                 channel_id: chan.2,
6920                 htlc_id: 0,
6921                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6922         };
6923
6924         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6925
6926         assert!(nodes[0].node.list_channels().is_empty());
6927         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6928         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()));
6929         check_added_monitors!(nodes[0], 1);
6930         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6931 }
6932
6933 #[test]
6934 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6935         //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.
6936
6937         let chanmon_cfgs = create_chanmon_cfgs(2);
6938         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6939         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6940         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6941         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6942
6943         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6944         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6945         check_added_monitors!(nodes[0], 1);
6946         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6947         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6948         let update_msg = msgs::UpdateFailMalformedHTLC{
6949                 channel_id: chan.2,
6950                 htlc_id: 0,
6951                 sha256_of_onion: [1; 32],
6952                 failure_code: 0x8000,
6953         };
6954
6955         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6956
6957         assert!(nodes[0].node.list_channels().is_empty());
6958         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6959         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()));
6960         check_added_monitors!(nodes[0], 1);
6961         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6962 }
6963
6964 #[test]
6965 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6966         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6967
6968         let chanmon_cfgs = create_chanmon_cfgs(2);
6969         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6970         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6971         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6972         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6973
6974         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6975
6976         nodes[1].node.claim_funds(our_payment_preimage);
6977         check_added_monitors!(nodes[1], 1);
6978         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6979
6980         let events = nodes[1].node.get_and_clear_pending_msg_events();
6981         assert_eq!(events.len(), 1);
6982         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6983                 match events[0] {
6984                         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, .. } } => {
6985                                 assert!(update_add_htlcs.is_empty());
6986                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6987                                 assert!(update_fail_htlcs.is_empty());
6988                                 assert!(update_fail_malformed_htlcs.is_empty());
6989                                 assert!(update_fee.is_none());
6990                                 update_fulfill_htlcs[0].clone()
6991                         },
6992                         _ => panic!("Unexpected event"),
6993                 }
6994         };
6995
6996         update_fulfill_msg.htlc_id = 1;
6997
6998         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6999
7000         assert!(nodes[0].node.list_channels().is_empty());
7001         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7002         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
7003         check_added_monitors!(nodes[0], 1);
7004         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7005 }
7006
7007 #[test]
7008 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
7009         //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.
7010
7011         let chanmon_cfgs = create_chanmon_cfgs(2);
7012         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7013         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7014         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7015         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7016
7017         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
7018
7019         nodes[1].node.claim_funds(our_payment_preimage);
7020         check_added_monitors!(nodes[1], 1);
7021         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
7022
7023         let events = nodes[1].node.get_and_clear_pending_msg_events();
7024         assert_eq!(events.len(), 1);
7025         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
7026                 match events[0] {
7027                         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, .. } } => {
7028                                 assert!(update_add_htlcs.is_empty());
7029                                 assert_eq!(update_fulfill_htlcs.len(), 1);
7030                                 assert!(update_fail_htlcs.is_empty());
7031                                 assert!(update_fail_malformed_htlcs.is_empty());
7032                                 assert!(update_fee.is_none());
7033                                 update_fulfill_htlcs[0].clone()
7034                         },
7035                         _ => panic!("Unexpected event"),
7036                 }
7037         };
7038
7039         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
7040
7041         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
7042
7043         assert!(nodes[0].node.list_channels().is_empty());
7044         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7045         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
7046         check_added_monitors!(nodes[0], 1);
7047         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7048 }
7049
7050 #[test]
7051 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
7052         //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.
7053
7054         let chanmon_cfgs = create_chanmon_cfgs(2);
7055         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7056         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7057         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7058         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7059
7060         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
7061         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7062         check_added_monitors!(nodes[0], 1);
7063
7064         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7065         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7066
7067         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
7068         check_added_monitors!(nodes[1], 0);
7069         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
7070
7071         let events = nodes[1].node.get_and_clear_pending_msg_events();
7072
7073         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
7074                 match events[0] {
7075                         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, .. } } => {
7076                                 assert!(update_add_htlcs.is_empty());
7077                                 assert!(update_fulfill_htlcs.is_empty());
7078                                 assert!(update_fail_htlcs.is_empty());
7079                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7080                                 assert!(update_fee.is_none());
7081                                 update_fail_malformed_htlcs[0].clone()
7082                         },
7083                         _ => panic!("Unexpected event"),
7084                 }
7085         };
7086         update_msg.failure_code &= !0x8000;
7087         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
7088
7089         assert!(nodes[0].node.list_channels().is_empty());
7090         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7091         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
7092         check_added_monitors!(nodes[0], 1);
7093         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7094 }
7095
7096 #[test]
7097 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
7098         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
7099         //    * 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.
7100
7101         let chanmon_cfgs = create_chanmon_cfgs(3);
7102         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7103         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7104         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7105         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7106         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7107
7108         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
7109
7110         //First hop
7111         let mut payment_event = {
7112                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7113                 check_added_monitors!(nodes[0], 1);
7114                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7115                 assert_eq!(events.len(), 1);
7116                 SendEvent::from_event(events.remove(0))
7117         };
7118         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7119         check_added_monitors!(nodes[1], 0);
7120         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7121         expect_pending_htlcs_forwardable!(nodes[1]);
7122         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7123         assert_eq!(events_2.len(), 1);
7124         check_added_monitors!(nodes[1], 1);
7125         payment_event = SendEvent::from_event(events_2.remove(0));
7126         assert_eq!(payment_event.msgs.len(), 1);
7127
7128         //Second Hop
7129         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7130         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7131         check_added_monitors!(nodes[2], 0);
7132         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7133
7134         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7135         assert_eq!(events_3.len(), 1);
7136         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
7137                 match events_3[0] {
7138                         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 } } => {
7139                                 assert!(update_add_htlcs.is_empty());
7140                                 assert!(update_fulfill_htlcs.is_empty());
7141                                 assert!(update_fail_htlcs.is_empty());
7142                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7143                                 assert!(update_fee.is_none());
7144                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
7145                         },
7146                         _ => panic!("Unexpected event"),
7147                 }
7148         };
7149
7150         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
7151
7152         check_added_monitors!(nodes[1], 0);
7153         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
7154         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 }]);
7155         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7156         assert_eq!(events_4.len(), 1);
7157
7158         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7159         match events_4[0] {
7160                 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, .. } } => {
7161                         assert!(update_add_htlcs.is_empty());
7162                         assert!(update_fulfill_htlcs.is_empty());
7163                         assert_eq!(update_fail_htlcs.len(), 1);
7164                         assert!(update_fail_malformed_htlcs.is_empty());
7165                         assert!(update_fee.is_none());
7166                 },
7167                 _ => panic!("Unexpected event"),
7168         };
7169
7170         check_added_monitors!(nodes[1], 1);
7171 }
7172
7173 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7174         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7175         // 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
7176         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7177
7178         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7179         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7180         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7181         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7182         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7183         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7184
7185         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7186
7187         // We route 2 dust-HTLCs between A and B
7188         let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7189         let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7190         route_payment(&nodes[0], &[&nodes[1]], 1000000);
7191
7192         // Cache one local commitment tx as previous
7193         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7194
7195         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7196         nodes[1].node.fail_htlc_backwards(&payment_hash_2);
7197         check_added_monitors!(nodes[1], 0);
7198         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7199         check_added_monitors!(nodes[1], 1);
7200
7201         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7202         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7203         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7204         check_added_monitors!(nodes[0], 1);
7205
7206         // Cache one local commitment tx as lastest
7207         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7208
7209         let events = nodes[0].node.get_and_clear_pending_msg_events();
7210         match events[0] {
7211                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7212                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7213                 },
7214                 _ => panic!("Unexpected event"),
7215         }
7216         match events[1] {
7217                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7218                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7219                 },
7220                 _ => panic!("Unexpected event"),
7221         }
7222
7223         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7224         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7225         if announce_latest {
7226                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7227         } else {
7228                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7229         }
7230
7231         check_closed_broadcast!(nodes[0], true);
7232         check_added_monitors!(nodes[0], 1);
7233         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7234
7235         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7236         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7237         let events = nodes[0].node.get_and_clear_pending_events();
7238         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7239         assert_eq!(events.len(), 2);
7240         let mut first_failed = false;
7241         for event in events {
7242                 match event {
7243                         Event::PaymentPathFailed { payment_hash, .. } => {
7244                                 if payment_hash == payment_hash_1 {
7245                                         assert!(!first_failed);
7246                                         first_failed = true;
7247                                 } else {
7248                                         assert_eq!(payment_hash, payment_hash_2);
7249                                 }
7250                         }
7251                         _ => panic!("Unexpected event"),
7252                 }
7253         }
7254 }
7255
7256 #[test]
7257 fn test_failure_delay_dust_htlc_local_commitment() {
7258         do_test_failure_delay_dust_htlc_local_commitment(true);
7259         do_test_failure_delay_dust_htlc_local_commitment(false);
7260 }
7261
7262 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7263         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7264         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7265         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7266         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7267         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7268         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7269
7270         let chanmon_cfgs = create_chanmon_cfgs(3);
7271         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7272         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7273         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7274         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7275
7276         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7277
7278         let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7279         let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7280
7281         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7282         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7283
7284         // We revoked bs_commitment_tx
7285         if revoked {
7286                 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7287                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7288         }
7289
7290         let mut timeout_tx = Vec::new();
7291         if local {
7292                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7293                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7294                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7295                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7296                 expect_payment_failed!(nodes[0], dust_hash, true);
7297
7298                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7299                 check_closed_broadcast!(nodes[0], true);
7300                 check_added_monitors!(nodes[0], 1);
7301                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7302                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7303                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7304                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7305                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7306                 mine_transaction(&nodes[0], &timeout_tx[0]);
7307                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7308                 expect_payment_failed!(nodes[0], non_dust_hash, true);
7309         } else {
7310                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7311                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7312                 check_closed_broadcast!(nodes[0], true);
7313                 check_added_monitors!(nodes[0], 1);
7314                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7315                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7316
7317                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7318                 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
7319                         .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
7320                 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
7321                 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
7322                 // dust HTLC should have been failed.
7323                 expect_payment_failed!(nodes[0], dust_hash, true);
7324
7325                 if !revoked {
7326                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7327                 } else {
7328                         assert_eq!(timeout_tx[0].lock_time.0, 0);
7329                 }
7330                 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
7331                 mine_transaction(&nodes[0], &timeout_tx[0]);
7332                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7333                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7334                 expect_payment_failed!(nodes[0], non_dust_hash, true);
7335         }
7336 }
7337
7338 #[test]
7339 fn test_sweep_outbound_htlc_failure_update() {
7340         do_test_sweep_outbound_htlc_failure_update(false, true);
7341         do_test_sweep_outbound_htlc_failure_update(false, false);
7342         do_test_sweep_outbound_htlc_failure_update(true, false);
7343 }
7344
7345 #[test]
7346 fn test_user_configurable_csv_delay() {
7347         // We test our channel constructors yield errors when we pass them absurd csv delay
7348
7349         let mut low_our_to_self_config = UserConfig::default();
7350         low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
7351         let mut high_their_to_self_config = UserConfig::default();
7352         high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
7353         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7354         let chanmon_cfgs = create_chanmon_cfgs(2);
7355         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7356         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7357         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7358
7359         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7360         if let Err(error) = Channel::new_outbound(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7361                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), 1000000, 1000000, 0,
7362                 &low_our_to_self_config, 0, 42)
7363         {
7364                 match error {
7365                         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())); },
7366                         _ => panic!("Unexpected event"),
7367                 }
7368         } else { assert!(false) }
7369
7370         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7371         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7372         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7373         open_channel.to_self_delay = 200;
7374         if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7375                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7376                 &low_our_to_self_config, 0, &nodes[0].logger, 42)
7377         {
7378                 match error {
7379                         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()));  },
7380                         _ => panic!("Unexpected event"),
7381                 }
7382         } else { assert!(false); }
7383
7384         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7385         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7386         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()));
7387         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7388         accept_channel.to_self_delay = 200;
7389         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7390         let reason_msg;
7391         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7392                 match action {
7393                         &ErrorAction::SendErrorMessage { ref msg } => {
7394                                 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()));
7395                                 reason_msg = msg.data.clone();
7396                         },
7397                         _ => { panic!(); }
7398                 }
7399         } else { panic!(); }
7400         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7401
7402         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7403         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7404         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7405         open_channel.to_self_delay = 200;
7406         if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7407                 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7408                 &high_their_to_self_config, 0, &nodes[0].logger, 42)
7409         {
7410                 match error {
7411                         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())); },
7412                         _ => panic!("Unexpected event"),
7413                 }
7414         } else { assert!(false); }
7415 }
7416
7417 fn do_test_data_loss_protect(reconnect_panicing: bool) {
7418         // When we get a data_loss_protect proving we're behind, we immediately panic as the
7419         // chain::Watch API requirements have been violated (e.g. the user restored from a backup). The
7420         // panic message informs the user they should force-close without broadcasting, which is tested
7421         // if `reconnect_panicing` is not set.
7422         let persister;
7423         let logger;
7424         let fee_estimator;
7425         let tx_broadcaster;
7426         let chain_source;
7427         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7428         // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7429         // during signing due to revoked tx
7430         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7431         let keys_manager = &chanmon_cfgs[0].keys_manager;
7432         let monitor;
7433         let node_state_0;
7434         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7435         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7436         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7437
7438         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7439
7440         // Cache node A state before any channel update
7441         let previous_node_state = nodes[0].node.encode();
7442         let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7443         get_monitor!(nodes[0], chan.2).write(&mut previous_chain_monitor_state).unwrap();
7444
7445         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7446         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7447
7448         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7449         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7450
7451         // Restore node A from previous state
7452         logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7453         let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7454         chain_source = test_utils::TestChainSource::new(Network::Testnet);
7455         tx_broadcaster = test_utils::TestBroadcaster { txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new())) };
7456         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7457         persister = test_utils::TestPersister::new();
7458         monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7459         node_state_0 = {
7460                 let mut channel_monitors = HashMap::new();
7461                 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7462                 <(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 {
7463                         keys_manager: keys_manager,
7464                         fee_estimator: &fee_estimator,
7465                         chain_monitor: &monitor,
7466                         logger: &logger,
7467                         tx_broadcaster: &tx_broadcaster,
7468                         default_config: UserConfig::default(),
7469                         channel_monitors,
7470                 }).unwrap().1
7471         };
7472         nodes[0].node = &node_state_0;
7473         assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7474         nodes[0].chain_monitor = &monitor;
7475         nodes[0].chain_source = &chain_source;
7476
7477         check_added_monitors!(nodes[0], 1);
7478
7479         if reconnect_panicing {
7480                 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7481                 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7482
7483                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7484
7485                 // Check we close channel detecting A is fallen-behind
7486                 // Check that we sent the warning message when we detected that A has fallen behind,
7487                 // and give the possibility for A to recover from the warning.
7488                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7489                 let warn_msg = "Peer attempted to reestablish channel with a very old local commitment transaction".to_owned();
7490                 assert!(check_warn_msg!(nodes[1], nodes[0].node.get_our_node_id(), chan.2).contains(&warn_msg));
7491
7492                 {
7493                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7494                         // The node B should not broadcast the transaction to force close the channel!
7495                         assert!(node_txn.is_empty());
7496                 }
7497
7498                 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7499                 // Check A panics upon seeing proof it has fallen behind.
7500                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7501                 return; // By this point we should have panic'ed!
7502         }
7503
7504         nodes[0].node.force_close_without_broadcasting_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
7505         check_added_monitors!(nodes[0], 1);
7506         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
7507         {
7508                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7509                 assert_eq!(node_txn.len(), 0);
7510         }
7511
7512         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7513                 if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7514                 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7515                         match action {
7516                                 &ErrorAction::SendErrorMessage { ref msg } => {
7517                                         assert_eq!(msg.data, "Channel force-closed");
7518                                 },
7519                                 _ => panic!("Unexpected event!"),
7520                         }
7521                 } else {
7522                         panic!("Unexpected event {:?}", msg)
7523                 }
7524         }
7525
7526         // after the warning message sent by B, we should not able to
7527         // use the channel, or reconnect with success to the channel.
7528         assert!(nodes[0].node.list_usable_channels().is_empty());
7529         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7530         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7531         let retry_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7532
7533         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &retry_reestablish[0]);
7534         let mut err_msgs_0 = Vec::with_capacity(1);
7535         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7536                 if let MessageSendEvent::HandleError { ref action, .. } = msg {
7537                         match action {
7538                                 &ErrorAction::SendErrorMessage { ref msg } => {
7539                                         assert_eq!(msg.data, "Failed to find corresponding channel");
7540                                         err_msgs_0.push(msg.clone());
7541                                 },
7542                                 _ => panic!("Unexpected event!"),
7543                         }
7544                 } else {
7545                         panic!("Unexpected event!");
7546                 }
7547         }
7548         assert_eq!(err_msgs_0.len(), 1);
7549         nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), &err_msgs_0[0]);
7550         assert!(nodes[1].node.list_usable_channels().is_empty());
7551         check_added_monitors!(nodes[1], 1);
7552         check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "Failed to find corresponding channel".to_owned() });
7553         check_closed_broadcast!(nodes[1], false);
7554 }
7555
7556 #[test]
7557 #[should_panic]
7558 fn test_data_loss_protect_showing_stale_state_panics() {
7559         do_test_data_loss_protect(true);
7560 }
7561
7562 #[test]
7563 fn test_force_close_without_broadcast() {
7564         do_test_data_loss_protect(false);
7565 }
7566
7567 #[test]
7568 fn test_check_htlc_underpaying() {
7569         // Send payment through A -> B but A is maliciously
7570         // sending a probe payment (i.e less than expected value0
7571         // to B, B should refuse payment.
7572
7573         let chanmon_cfgs = create_chanmon_cfgs(2);
7574         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7575         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7576         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7577
7578         // Create some initial channels
7579         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7580
7581         let scorer = test_utils::TestScorer::with_penalty(0);
7582         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7583         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7584         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();
7585         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7586         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200).unwrap();
7587         nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7588         check_added_monitors!(nodes[0], 1);
7589
7590         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7591         assert_eq!(events.len(), 1);
7592         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7593         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7594         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7595
7596         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7597         // and then will wait a second random delay before failing the HTLC back:
7598         expect_pending_htlcs_forwardable!(nodes[1]);
7599         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7600
7601         // Node 3 is expecting payment of 100_000 but received 10_000,
7602         // it should fail htlc like we didn't know the preimage.
7603         nodes[1].node.process_pending_htlc_forwards();
7604
7605         let events = nodes[1].node.get_and_clear_pending_msg_events();
7606         assert_eq!(events.len(), 1);
7607         let (update_fail_htlc, commitment_signed) = match events[0] {
7608                 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 } } => {
7609                         assert!(update_add_htlcs.is_empty());
7610                         assert!(update_fulfill_htlcs.is_empty());
7611                         assert_eq!(update_fail_htlcs.len(), 1);
7612                         assert!(update_fail_malformed_htlcs.is_empty());
7613                         assert!(update_fee.is_none());
7614                         (update_fail_htlcs[0].clone(), commitment_signed)
7615                 },
7616                 _ => panic!("Unexpected event"),
7617         };
7618         check_added_monitors!(nodes[1], 1);
7619
7620         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7621         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7622
7623         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7624         let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7625         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7626         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7627 }
7628
7629 #[test]
7630 fn test_announce_disable_channels() {
7631         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7632         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7633
7634         let chanmon_cfgs = create_chanmon_cfgs(2);
7635         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7636         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7637         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7638
7639         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7640         create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known());
7641         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7642
7643         // Disconnect peers
7644         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7645         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7646
7647         nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7648         nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7649         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7650         assert_eq!(msg_events.len(), 3);
7651         let mut chans_disabled = HashMap::new();
7652         for e in msg_events {
7653                 match e {
7654                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7655                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7656                                 // Check that each channel gets updated exactly once
7657                                 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7658                                         panic!("Generated ChannelUpdate for wrong chan!");
7659                                 }
7660                         },
7661                         _ => panic!("Unexpected event"),
7662                 }
7663         }
7664         // Reconnect peers
7665         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7666         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7667         assert_eq!(reestablish_1.len(), 3);
7668         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7669         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7670         assert_eq!(reestablish_2.len(), 3);
7671
7672         // Reestablish chan_1
7673         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7674         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7675         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7676         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7677         // Reestablish chan_2
7678         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7679         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7680         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7681         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7682         // Reestablish chan_3
7683         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
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[2]);
7686         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7687
7688         nodes[0].node.timer_tick_occurred();
7689         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7690         nodes[0].node.timer_tick_occurred();
7691         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7692         assert_eq!(msg_events.len(), 3);
7693         for e in msg_events {
7694                 match e {
7695                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7696                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7697                                 match chans_disabled.remove(&msg.contents.short_channel_id) {
7698                                         // Each update should have a higher timestamp than the previous one, replacing
7699                                         // the old one.
7700                                         Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7701                                         None => panic!("Generated ChannelUpdate for wrong chan!"),
7702                                 }
7703                         },
7704                         _ => panic!("Unexpected event"),
7705                 }
7706         }
7707         // Check that each channel gets updated exactly once
7708         assert!(chans_disabled.is_empty());
7709 }
7710
7711 #[test]
7712 fn test_bump_penalty_txn_on_revoked_commitment() {
7713         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7714         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7715
7716         let chanmon_cfgs = create_chanmon_cfgs(2);
7717         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7718         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7719         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7720
7721         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7722
7723         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7724         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id())
7725                 .with_features(InvoiceFeatures::known());
7726         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7727         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7728
7729         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7730         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7731         assert_eq!(revoked_txn[0].output.len(), 4);
7732         assert_eq!(revoked_txn[0].input.len(), 1);
7733         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7734         let revoked_txid = revoked_txn[0].txid();
7735
7736         let mut penalty_sum = 0;
7737         for outp in revoked_txn[0].output.iter() {
7738                 if outp.script_pubkey.is_v0_p2wsh() {
7739                         penalty_sum += outp.value;
7740                 }
7741         }
7742
7743         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7744         let header_114 = connect_blocks(&nodes[1], 14);
7745
7746         // Actually revoke tx by claiming a HTLC
7747         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7748         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7749         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7750         check_added_monitors!(nodes[1], 1);
7751
7752         // One or more justice tx should have been broadcast, check it
7753         let penalty_1;
7754         let feerate_1;
7755         {
7756                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7757                 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7758                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7759                 assert_eq!(node_txn[0].output.len(), 1);
7760                 check_spends!(node_txn[0], revoked_txn[0]);
7761                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7762                 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7763                 penalty_1 = node_txn[0].txid();
7764                 node_txn.clear();
7765         };
7766
7767         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7768         connect_blocks(&nodes[1], 15);
7769         let mut penalty_2 = penalty_1;
7770         let mut feerate_2 = 0;
7771         {
7772                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7773                 assert_eq!(node_txn.len(), 1);
7774                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7775                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7776                         assert_eq!(node_txn[0].output.len(), 1);
7777                         check_spends!(node_txn[0], revoked_txn[0]);
7778                         penalty_2 = node_txn[0].txid();
7779                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7780                         assert_ne!(penalty_2, penalty_1);
7781                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7782                         feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7783                         // Verify 25% bump heuristic
7784                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7785                         node_txn.clear();
7786                 }
7787         }
7788         assert_ne!(feerate_2, 0);
7789
7790         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7791         connect_blocks(&nodes[1], 1);
7792         let penalty_3;
7793         let mut feerate_3 = 0;
7794         {
7795                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7796                 assert_eq!(node_txn.len(), 1);
7797                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7798                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7799                         assert_eq!(node_txn[0].output.len(), 1);
7800                         check_spends!(node_txn[0], revoked_txn[0]);
7801                         penalty_3 = node_txn[0].txid();
7802                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7803                         assert_ne!(penalty_3, penalty_2);
7804                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7805                         feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7806                         // Verify 25% bump heuristic
7807                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7808                         node_txn.clear();
7809                 }
7810         }
7811         assert_ne!(feerate_3, 0);
7812
7813         nodes[1].node.get_and_clear_pending_events();
7814         nodes[1].node.get_and_clear_pending_msg_events();
7815 }
7816
7817 #[test]
7818 fn test_bump_penalty_txn_on_revoked_htlcs() {
7819         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7820         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7821
7822         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7823         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7824         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7825         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7826         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7827
7828         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7829         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7830         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7831         let scorer = test_utils::TestScorer::with_penalty(0);
7832         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7833         let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7834                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7835         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7836         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7837         let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7838                 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7839         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7840
7841         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7842         assert_eq!(revoked_local_txn[0].input.len(), 1);
7843         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7844
7845         // Revoke local commitment tx
7846         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7847
7848         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7849         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7850         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7851         check_closed_broadcast!(nodes[1], true);
7852         check_added_monitors!(nodes[1], 1);
7853         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7854         connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7855
7856         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
7857         assert_eq!(revoked_htlc_txn.len(), 3);
7858         check_spends!(revoked_htlc_txn[1], chan.3);
7859
7860         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7861         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7862         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7863
7864         assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7865         assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7866         assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7867         check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7868
7869         // Broadcast set of revoked txn on A
7870         let hash_128 = connect_blocks(&nodes[0], 40);
7871         let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7872         connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7873         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7874         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7875         let events = nodes[0].node.get_and_clear_pending_events();
7876         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7877         match events.last().unwrap() {
7878                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7879                 _ => panic!("Unexpected event"),
7880         }
7881         let first;
7882         let feerate_1;
7883         let penalty_txn;
7884         {
7885                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7886                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7887                 // Verify claim tx are spending revoked HTLC txn
7888
7889                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7890                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7891                 // which are included in the same block (they are broadcasted because we scan the
7892                 // transactions linearly and generate claims as we go, they likely should be removed in the
7893                 // future).
7894                 assert_eq!(node_txn[0].input.len(), 1);
7895                 check_spends!(node_txn[0], revoked_local_txn[0]);
7896                 assert_eq!(node_txn[1].input.len(), 1);
7897                 check_spends!(node_txn[1], revoked_local_txn[0]);
7898                 assert_eq!(node_txn[2].input.len(), 1);
7899                 check_spends!(node_txn[2], revoked_local_txn[0]);
7900
7901                 // Each of the three justice transactions claim a separate (single) output of the three
7902                 // available, which we check here:
7903                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7904                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7905                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7906
7907                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7908                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7909
7910                 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7911                 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7912                 // a remote commitment tx has already been confirmed).
7913                 check_spends!(node_txn[3], chan.3);
7914
7915                 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7916                 // output, checked above).
7917                 assert_eq!(node_txn[4].input.len(), 2);
7918                 assert_eq!(node_txn[4].output.len(), 1);
7919                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7920
7921                 first = node_txn[4].txid();
7922                 // Store both feerates for later comparison
7923                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7924                 feerate_1 = fee_1 * 1000 / node_txn[4].weight() as u64;
7925                 penalty_txn = vec![node_txn[2].clone()];
7926                 node_txn.clear();
7927         }
7928
7929         // Connect one more block to see if bumped penalty are issued for HTLC txn
7930         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7931         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7932         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7933         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7934         {
7935                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7936                 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7937
7938                 check_spends!(node_txn[0], revoked_local_txn[0]);
7939                 check_spends!(node_txn[1], revoked_local_txn[0]);
7940                 // Note that these are both bogus - they spend outputs already claimed in block 129:
7941                 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output  {
7942                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7943                 } else {
7944                         assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7945                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7946                 }
7947
7948                 node_txn.clear();
7949         };
7950
7951         // Few more blocks to confirm penalty txn
7952         connect_blocks(&nodes[0], 4);
7953         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7954         let header_144 = connect_blocks(&nodes[0], 9);
7955         let node_txn = {
7956                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7957                 assert_eq!(node_txn.len(), 1);
7958
7959                 assert_eq!(node_txn[0].input.len(), 2);
7960                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7961                 // Verify bumped tx is different and 25% bump heuristic
7962                 assert_ne!(first, node_txn[0].txid());
7963                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
7964                 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7965                 assert!(feerate_2 * 100 > feerate_1 * 125);
7966                 let txn = vec![node_txn[0].clone()];
7967                 node_txn.clear();
7968                 txn
7969         };
7970         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7971         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7972         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7973         connect_blocks(&nodes[0], 20);
7974         {
7975                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7976                 // We verify than no new transaction has been broadcast because previously
7977                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7978                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7979                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7980                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7981                 // up bumped justice generation.
7982                 assert_eq!(node_txn.len(), 0);
7983                 node_txn.clear();
7984         }
7985         check_closed_broadcast!(nodes[0], true);
7986         check_added_monitors!(nodes[0], 1);
7987 }
7988
7989 #[test]
7990 fn test_bump_penalty_txn_on_remote_commitment() {
7991         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7992         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7993
7994         // Create 2 HTLCs
7995         // Provide preimage for one
7996         // Check aggregation
7997
7998         let chanmon_cfgs = create_chanmon_cfgs(2);
7999         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8000         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8001         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8002
8003         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8004         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
8005         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
8006
8007         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
8008         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
8009         assert_eq!(remote_txn[0].output.len(), 4);
8010         assert_eq!(remote_txn[0].input.len(), 1);
8011         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
8012
8013         // Claim a HTLC without revocation (provide B monitor with preimage)
8014         nodes[1].node.claim_funds(payment_preimage);
8015         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
8016         mine_transaction(&nodes[1], &remote_txn[0]);
8017         check_added_monitors!(nodes[1], 2);
8018         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
8019
8020         // One or more claim tx should have been broadcast, check it
8021         let timeout;
8022         let preimage;
8023         let preimage_bump;
8024         let feerate_timeout;
8025         let feerate_preimage;
8026         {
8027                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8028                 // 9 transactions including:
8029                 // 1*2 ChannelManager local broadcasts of commitment + HTLC-Success
8030                 // 1*3 ChannelManager local broadcasts of commitment + HTLC-Success + HTLC-Timeout
8031                 // 2 * HTLC-Success (one RBF bump we'll check later)
8032                 // 1 * HTLC-Timeout
8033                 assert_eq!(node_txn.len(), 8);
8034                 assert_eq!(node_txn[0].input.len(), 1);
8035                 assert_eq!(node_txn[6].input.len(), 1);
8036                 check_spends!(node_txn[0], remote_txn[0]);
8037                 check_spends!(node_txn[6], remote_txn[0]);
8038
8039                 check_spends!(node_txn[1], chan.3);
8040                 check_spends!(node_txn[2], node_txn[1]);
8041
8042                 if node_txn[0].input[0].previous_output == node_txn[3].input[0].previous_output {
8043                         preimage_bump = node_txn[3].clone();
8044                         check_spends!(node_txn[3], remote_txn[0]);
8045
8046                         assert_eq!(node_txn[1], node_txn[4]);
8047                         assert_eq!(node_txn[2], node_txn[5]);
8048                 } else {
8049                         preimage_bump = node_txn[7].clone();
8050                         check_spends!(node_txn[7], remote_txn[0]);
8051                         assert_eq!(node_txn[0].input[0].previous_output, node_txn[7].input[0].previous_output);
8052
8053                         assert_eq!(node_txn[1], node_txn[3]);
8054                         assert_eq!(node_txn[2], node_txn[4]);
8055                 }
8056
8057                 timeout = node_txn[6].txid();
8058                 let index = node_txn[6].input[0].previous_output.vout;
8059                 let fee = remote_txn[0].output[index as usize].value - node_txn[6].output[0].value;
8060                 feerate_timeout = fee * 1000 / node_txn[6].weight() as u64;
8061
8062                 preimage = node_txn[0].txid();
8063                 let index = node_txn[0].input[0].previous_output.vout;
8064                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8065                 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
8066
8067                 node_txn.clear();
8068         };
8069         assert_ne!(feerate_timeout, 0);
8070         assert_ne!(feerate_preimage, 0);
8071
8072         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
8073         connect_blocks(&nodes[1], 15);
8074         {
8075                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8076                 assert_eq!(node_txn.len(), 1);
8077                 assert_eq!(node_txn[0].input.len(), 1);
8078                 assert_eq!(preimage_bump.input.len(), 1);
8079                 check_spends!(node_txn[0], remote_txn[0]);
8080                 check_spends!(preimage_bump, remote_txn[0]);
8081
8082                 let index = preimage_bump.input[0].previous_output.vout;
8083                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
8084                 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
8085                 assert!(new_feerate * 100 > feerate_timeout * 125);
8086                 assert_ne!(timeout, preimage_bump.txid());
8087
8088                 let index = node_txn[0].input[0].previous_output.vout;
8089                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8090                 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
8091                 assert!(new_feerate * 100 > feerate_preimage * 125);
8092                 assert_ne!(preimage, node_txn[0].txid());
8093
8094                 node_txn.clear();
8095         }
8096
8097         nodes[1].node.get_and_clear_pending_events();
8098         nodes[1].node.get_and_clear_pending_msg_events();
8099 }
8100
8101 #[test]
8102 fn test_counterparty_raa_skip_no_crash() {
8103         // Previously, if our counterparty sent two RAAs in a row without us having provided a
8104         // commitment transaction, we would have happily carried on and provided them the next
8105         // commitment transaction based on one RAA forward. This would probably eventually have led to
8106         // channel closure, but it would not have resulted in funds loss. Still, our
8107         // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
8108         // check simply that the channel is closed in response to such an RAA, but don't check whether
8109         // we decide to punish our counterparty for revoking their funds (as we don't currently
8110         // implement that).
8111         let chanmon_cfgs = create_chanmon_cfgs(2);
8112         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8113         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8114         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8115         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8116
8117         let per_commitment_secret;
8118         let next_per_commitment_point;
8119         {
8120                 let mut guard = nodes[0].node.channel_state.lock().unwrap();
8121                 let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
8122
8123                 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8124
8125                 // Make signer believe we got a counterparty signature, so that it allows the revocation
8126                 keys.get_enforcement_state().last_holder_commitment -= 1;
8127                 per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8128
8129                 // Must revoke without gaps
8130                 keys.get_enforcement_state().last_holder_commitment -= 1;
8131                 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8132
8133                 keys.get_enforcement_state().last_holder_commitment -= 1;
8134                 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8135                         &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8136         }
8137
8138         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8139                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8140         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8141         check_added_monitors!(nodes[1], 1);
8142         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
8143 }
8144
8145 #[test]
8146 fn test_bump_txn_sanitize_tracking_maps() {
8147         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8148         // verify we clean then right after expiration of ANTI_REORG_DELAY.
8149
8150         let chanmon_cfgs = create_chanmon_cfgs(2);
8151         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8152         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8153         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8154
8155         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8156         // Lock HTLC in both directions
8157         let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
8158         let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
8159
8160         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8161         assert_eq!(revoked_local_txn[0].input.len(), 1);
8162         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8163
8164         // Revoke local commitment tx
8165         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
8166
8167         // Broadcast set of revoked txn on A
8168         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
8169         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
8170         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8171
8172         mine_transaction(&nodes[0], &revoked_local_txn[0]);
8173         check_closed_broadcast!(nodes[0], true);
8174         check_added_monitors!(nodes[0], 1);
8175         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8176         let penalty_txn = {
8177                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8178                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8179                 check_spends!(node_txn[0], revoked_local_txn[0]);
8180                 check_spends!(node_txn[1], revoked_local_txn[0]);
8181                 check_spends!(node_txn[2], revoked_local_txn[0]);
8182                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8183                 node_txn.clear();
8184                 penalty_txn
8185         };
8186         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8187         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8188         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8189         {
8190                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
8191                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8192                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8193         }
8194 }
8195
8196 #[test]
8197 fn test_pending_claimed_htlc_no_balance_underflow() {
8198         // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
8199         // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
8200         let chanmon_cfgs = create_chanmon_cfgs(2);
8201         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8202         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8203         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8204         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
8205
8206         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_010_000);
8207         nodes[1].node.claim_funds(payment_preimage);
8208         expect_payment_claimed!(nodes[1], payment_hash, 1_010_000);
8209         check_added_monitors!(nodes[1], 1);
8210         let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8211
8212         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
8213         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
8214         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
8215         check_added_monitors!(nodes[0], 1);
8216         let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
8217
8218         // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
8219         // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
8220         // can get our balance.
8221
8222         // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
8223         // the public key of the only hop. This works around ChannelDetails not showing the
8224         // almost-claimed HTLC as available balance.
8225         let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
8226         route.payment_params = None; // This is all wrong, but unnecessary
8227         route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
8228         let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
8229         nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
8230
8231         assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
8232 }
8233
8234 #[test]
8235 fn test_channel_conf_timeout() {
8236         // Tests that, for inbound channels, we give up on them if the funding transaction does not
8237         // confirm within 2016 blocks, as recommended by BOLT 2.
8238         let chanmon_cfgs = create_chanmon_cfgs(2);
8239         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8240         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8241         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8242
8243         let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000, InitFeatures::known(), InitFeatures::known());
8244
8245         // The outbound node should wait forever for confirmation:
8246         // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
8247         // copied here instead of directly referencing the constant.
8248         connect_blocks(&nodes[0], 2016);
8249         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8250
8251         // The inbound node should fail the channel after exactly 2016 blocks
8252         connect_blocks(&nodes[1], 2015);
8253         check_added_monitors!(nodes[1], 0);
8254         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8255
8256         connect_blocks(&nodes[1], 1);
8257         check_added_monitors!(nodes[1], 1);
8258         check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
8259         let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
8260         assert_eq!(close_ev.len(), 1);
8261         match close_ev[0] {
8262                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
8263                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8264                         assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
8265                 },
8266                 _ => panic!("Unexpected event"),
8267         }
8268 }
8269
8270 #[test]
8271 fn test_override_channel_config() {
8272         let chanmon_cfgs = create_chanmon_cfgs(2);
8273         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8274         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8275         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8276
8277         // Node0 initiates a channel to node1 using the override config.
8278         let mut override_config = UserConfig::default();
8279         override_config.channel_handshake_config.our_to_self_delay = 200;
8280
8281         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8282
8283         // Assert the channel created by node0 is using the override config.
8284         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8285         assert_eq!(res.channel_flags, 0);
8286         assert_eq!(res.to_self_delay, 200);
8287 }
8288
8289 #[test]
8290 fn test_override_0msat_htlc_minimum() {
8291         let mut zero_config = UserConfig::default();
8292         zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
8293         let chanmon_cfgs = create_chanmon_cfgs(2);
8294         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8295         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8296         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8297
8298         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8299         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8300         assert_eq!(res.htlc_minimum_msat, 1);
8301
8302         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8303         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8304         assert_eq!(res.htlc_minimum_msat, 1);
8305 }
8306
8307 #[test]
8308 fn test_channel_update_has_correct_htlc_maximum_msat() {
8309         // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
8310         // Bolt 7 specifies that if present `htlc_maximum_msat`:
8311         // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
8312         // 90% of the `channel_value`.
8313         // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
8314
8315         let mut config_30_percent = UserConfig::default();
8316         config_30_percent.channel_handshake_config.announced_channel = true;
8317         config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
8318         let mut config_50_percent = UserConfig::default();
8319         config_50_percent.channel_handshake_config.announced_channel = true;
8320         config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
8321         let mut config_95_percent = UserConfig::default();
8322         config_95_percent.channel_handshake_config.announced_channel = true;
8323         config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
8324         let mut config_100_percent = UserConfig::default();
8325         config_100_percent.channel_handshake_config.announced_channel = true;
8326         config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
8327
8328         let chanmon_cfgs = create_chanmon_cfgs(4);
8329         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8330         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)]);
8331         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8332
8333         let channel_value_satoshis = 100000;
8334         let channel_value_msat = channel_value_satoshis * 1000;
8335         let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
8336         let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
8337         let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
8338
8339         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());
8340         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());
8341
8342         // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
8343         // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
8344         assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
8345         // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
8346         // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
8347         assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
8348
8349         // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8350         // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
8351         // `channel_value`.
8352         assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
8353         // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8354         // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
8355         // `channel_value`.
8356         assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
8357 }
8358
8359 #[test]
8360 fn test_manually_accept_inbound_channel_request() {
8361         let mut manually_accept_conf = UserConfig::default();
8362         manually_accept_conf.manually_accept_inbound_channels = true;
8363         let chanmon_cfgs = create_chanmon_cfgs(2);
8364         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8365         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8366         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8367
8368         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8369         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8370
8371         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8372
8373         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8374         // accepting the inbound channel request.
8375         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8376
8377         let events = nodes[1].node.get_and_clear_pending_events();
8378         match events[0] {
8379                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8380                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
8381                 }
8382                 _ => panic!("Unexpected event"),
8383         }
8384
8385         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8386         assert_eq!(accept_msg_ev.len(), 1);
8387
8388         match accept_msg_ev[0] {
8389                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8390                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8391                 }
8392                 _ => panic!("Unexpected event"),
8393         }
8394
8395         nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8396
8397         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8398         assert_eq!(close_msg_ev.len(), 1);
8399
8400         let events = nodes[1].node.get_and_clear_pending_events();
8401         match events[0] {
8402                 Event::ChannelClosed { user_channel_id, .. } => {
8403                         assert_eq!(user_channel_id, 23);
8404                 }
8405                 _ => panic!("Unexpected event"),
8406         }
8407 }
8408
8409 #[test]
8410 fn test_manually_reject_inbound_channel_request() {
8411         let mut manually_accept_conf = UserConfig::default();
8412         manually_accept_conf.manually_accept_inbound_channels = true;
8413         let chanmon_cfgs = create_chanmon_cfgs(2);
8414         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8415         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8416         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8417
8418         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8419         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8420
8421         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8422
8423         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8424         // rejecting the inbound channel request.
8425         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8426
8427         let events = nodes[1].node.get_and_clear_pending_events();
8428         match events[0] {
8429                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8430                         nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8431                 }
8432                 _ => panic!("Unexpected event"),
8433         }
8434
8435         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8436         assert_eq!(close_msg_ev.len(), 1);
8437
8438         match close_msg_ev[0] {
8439                 MessageSendEvent::HandleError { ref node_id, .. } => {
8440                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8441                 }
8442                 _ => panic!("Unexpected event"),
8443         }
8444         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8445 }
8446
8447 #[test]
8448 fn test_reject_funding_before_inbound_channel_accepted() {
8449         // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
8450         // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
8451         // the node operator before the counterparty sends a `FundingCreated` message. If a
8452         // `FundingCreated` message is received before the channel is accepted, it should be rejected
8453         // and the channel should be closed.
8454         let mut manually_accept_conf = UserConfig::default();
8455         manually_accept_conf.manually_accept_inbound_channels = true;
8456         let chanmon_cfgs = create_chanmon_cfgs(2);
8457         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8458         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8459         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8460
8461         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8462         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8463         let temp_channel_id = res.temporary_channel_id;
8464
8465         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8466
8467         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
8468         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8469
8470         // Clear the `Event::OpenChannelRequest` event without responding to the request.
8471         nodes[1].node.get_and_clear_pending_events();
8472
8473         // Get the `AcceptChannel` message of `nodes[1]` without calling
8474         // `ChannelManager::accept_inbound_channel`, which generates a
8475         // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
8476         // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
8477         // succeed when `nodes[0]` is passed to it.
8478         let accept_chan_msg = {
8479                 let mut lock;
8480                 let channel = get_channel_ref!(&nodes[1], lock, temp_channel_id);
8481                 channel.get_accept_channel_message()
8482         };
8483         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8484
8485         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8486
8487         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8488         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8489
8490         // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
8491         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8492
8493         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8494         assert_eq!(close_msg_ev.len(), 1);
8495
8496         let expected_err = "FundingCreated message received before the channel was accepted";
8497         match close_msg_ev[0] {
8498                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
8499                         assert_eq!(msg.channel_id, temp_channel_id);
8500                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8501                         assert_eq!(msg.data, expected_err);
8502                 }
8503                 _ => panic!("Unexpected event"),
8504         }
8505
8506         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
8507 }
8508
8509 #[test]
8510 fn test_can_not_accept_inbound_channel_twice() {
8511         let mut manually_accept_conf = UserConfig::default();
8512         manually_accept_conf.manually_accept_inbound_channels = true;
8513         let chanmon_cfgs = create_chanmon_cfgs(2);
8514         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8515         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8516         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8517
8518         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8519         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8520
8521         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8522
8523         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8524         // accepting the inbound channel request.
8525         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8526
8527         let events = nodes[1].node.get_and_clear_pending_events();
8528         match events[0] {
8529                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8530                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
8531                         let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
8532                         match api_res {
8533                                 Err(APIError::APIMisuseError { err }) => {
8534                                         assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
8535                                 },
8536                                 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8537                                 Err(_) => panic!("Unexpected Error"),
8538                         }
8539                 }
8540                 _ => panic!("Unexpected event"),
8541         }
8542
8543         // Ensure that the channel wasn't closed after attempting to accept it twice.
8544         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8545         assert_eq!(accept_msg_ev.len(), 1);
8546
8547         match accept_msg_ev[0] {
8548                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8549                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8550                 }
8551                 _ => panic!("Unexpected event"),
8552         }
8553 }
8554
8555 #[test]
8556 fn test_can_not_accept_unknown_inbound_channel() {
8557         let chanmon_cfg = create_chanmon_cfgs(2);
8558         let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8559         let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8560         let nodes = create_network(2, &node_cfg, &node_chanmgr);
8561
8562         let unknown_channel_id = [0; 32];
8563         let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8564         match api_res {
8565                 Err(APIError::ChannelUnavailable { err }) => {
8566                         assert_eq!(err, "Can't accept a channel that doesn't exist");
8567                 },
8568                 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8569                 Err(_) => panic!("Unexpected Error"),
8570         }
8571 }
8572
8573 #[test]
8574 fn test_simple_mpp() {
8575         // Simple test of sending a multi-path payment.
8576         let chanmon_cfgs = create_chanmon_cfgs(4);
8577         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8578         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8579         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8580
8581         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8582         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8583         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8584         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8585
8586         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8587         let path = route.paths[0].clone();
8588         route.paths.push(path);
8589         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8590         route.paths[0][0].short_channel_id = chan_1_id;
8591         route.paths[0][1].short_channel_id = chan_3_id;
8592         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8593         route.paths[1][0].short_channel_id = chan_2_id;
8594         route.paths[1][1].short_channel_id = chan_4_id;
8595         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8596         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8597 }
8598
8599 #[test]
8600 fn test_preimage_storage() {
8601         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8602         let chanmon_cfgs = create_chanmon_cfgs(2);
8603         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8604         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8605         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8606
8607         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8608
8609         {
8610                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200).unwrap();
8611                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8612                 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8613                 check_added_monitors!(nodes[0], 1);
8614                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8615                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8616                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8617                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8618         }
8619         // Note that after leaving the above scope we have no knowledge of any arguments or return
8620         // values from previous calls.
8621         expect_pending_htlcs_forwardable!(nodes[1]);
8622         let events = nodes[1].node.get_and_clear_pending_events();
8623         assert_eq!(events.len(), 1);
8624         match events[0] {
8625                 Event::PaymentReceived { ref purpose, .. } => {
8626                         match &purpose {
8627                                 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8628                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8629                                 },
8630                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
8631                         }
8632                 },
8633                 _ => panic!("Unexpected event"),
8634         }
8635 }
8636
8637 #[test]
8638 #[allow(deprecated)]
8639 fn test_secret_timeout() {
8640         // Simple test of payment secret storage time outs. After
8641         // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8642         let chanmon_cfgs = create_chanmon_cfgs(2);
8643         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8644         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8645         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8646
8647         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8648
8649         let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8650
8651         // We should fail to register the same payment hash twice, at least until we've connected a
8652         // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8653         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8654                 assert_eq!(err, "Duplicate payment hash");
8655         } else { panic!(); }
8656         let mut block = {
8657                 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8658                 Block {
8659                         header: BlockHeader {
8660                                 version: 0x2000000,
8661                                 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8662                                 merkle_root: TxMerkleNode::all_zeros(),
8663                                 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8664                         txdata: vec![],
8665                 }
8666         };
8667         connect_block(&nodes[1], &block);
8668         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8669                 assert_eq!(err, "Duplicate payment hash");
8670         } else { panic!(); }
8671
8672         // If we then connect the second block, we should be able to register the same payment hash
8673         // again (this time getting a new payment secret).
8674         block.header.prev_blockhash = block.header.block_hash();
8675         block.header.time += 1;
8676         connect_block(&nodes[1], &block);
8677         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8678         assert_ne!(payment_secret_1, our_payment_secret);
8679
8680         {
8681                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8682                 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8683                 check_added_monitors!(nodes[0], 1);
8684                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8685                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8686                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8687                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8688         }
8689         // Note that after leaving the above scope we have no knowledge of any arguments or return
8690         // values from previous calls.
8691         expect_pending_htlcs_forwardable!(nodes[1]);
8692         let events = nodes[1].node.get_and_clear_pending_events();
8693         assert_eq!(events.len(), 1);
8694         match events[0] {
8695                 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8696                         assert!(payment_preimage.is_none());
8697                         assert_eq!(payment_secret, our_payment_secret);
8698                         // We don't actually have the payment preimage with which to claim this payment!
8699                 },
8700                 _ => panic!("Unexpected event"),
8701         }
8702 }
8703
8704 #[test]
8705 fn test_bad_secret_hash() {
8706         // Simple test of unregistered payment hash/invalid payment secret handling
8707         let chanmon_cfgs = create_chanmon_cfgs(2);
8708         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8709         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8710         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8711
8712         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8713
8714         let random_payment_hash = PaymentHash([42; 32]);
8715         let random_payment_secret = PaymentSecret([43; 32]);
8716         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2).unwrap();
8717         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8718
8719         // All the below cases should end up being handled exactly identically, so we macro the
8720         // resulting events.
8721         macro_rules! handle_unknown_invalid_payment_data {
8722                 ($payment_hash: expr) => {
8723                         check_added_monitors!(nodes[0], 1);
8724                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8725                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8726                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8727                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8728
8729                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8730                         // again to process the pending backwards-failure of the HTLC
8731                         expect_pending_htlcs_forwardable!(nodes[1]);
8732                         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8733                         check_added_monitors!(nodes[1], 1);
8734
8735                         // We should fail the payment back
8736                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8737                         match events.pop().unwrap() {
8738                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8739                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8740                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8741                                 },
8742                                 _ => panic!("Unexpected event"),
8743                         }
8744                 }
8745         }
8746
8747         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8748         // Error data is the HTLC value (100,000) and current block height
8749         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8750
8751         // Send a payment with the right payment hash but the wrong payment secret
8752         nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8753         handle_unknown_invalid_payment_data!(our_payment_hash);
8754         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8755
8756         // Send a payment with a random payment hash, but the right payment secret
8757         nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8758         handle_unknown_invalid_payment_data!(random_payment_hash);
8759         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8760
8761         // Send a payment with a random payment hash and random payment secret
8762         nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8763         handle_unknown_invalid_payment_data!(random_payment_hash);
8764         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8765 }
8766
8767 #[test]
8768 fn test_update_err_monitor_lockdown() {
8769         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8770         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8771         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8772         //
8773         // This scenario may happen in a watchtower setup, where watchtower process a block height
8774         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8775         // commitment at same time.
8776
8777         let chanmon_cfgs = create_chanmon_cfgs(2);
8778         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8779         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8780         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8781
8782         // Create some initial channel
8783         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8784         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8785
8786         // Rebalance the network to generate htlc in the two directions
8787         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8788
8789         // Route a HTLC from node 0 to node 1 (but don't settle)
8790         let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8791
8792         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8793         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8794         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8795         let persister = test_utils::TestPersister::new();
8796         let watchtower = {
8797                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8798                 let mut w = test_utils::TestVecWriter(Vec::new());
8799                 monitor.write(&mut w).unwrap();
8800                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8801                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8802                 assert!(new_monitor == *monitor);
8803                 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);
8804                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8805                 watchtower
8806         };
8807         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8808         let block = Block { header, txdata: vec![] };
8809         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8810         // transaction lock time requirements here.
8811         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 0));
8812         watchtower.chain_monitor.block_connected(&block, 200);
8813
8814         // Try to update ChannelMonitor
8815         nodes[1].node.claim_funds(preimage);
8816         check_added_monitors!(nodes[1], 1);
8817         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8818
8819         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8820         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8821         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8822         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8823                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8824                         if let Err(_) =  watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8825                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8826                 } else { assert!(false); }
8827         } else { assert!(false); };
8828         // Our local monitor is in-sync and hasn't processed yet timeout
8829         check_added_monitors!(nodes[0], 1);
8830         let events = nodes[0].node.get_and_clear_pending_events();
8831         assert_eq!(events.len(), 1);
8832 }
8833
8834 #[test]
8835 fn test_concurrent_monitor_claim() {
8836         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8837         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8838         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8839         // state N+1 confirms. Alice claims output from state N+1.
8840
8841         let chanmon_cfgs = create_chanmon_cfgs(2);
8842         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8843         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8844         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8845
8846         // Create some initial channel
8847         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8848         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8849
8850         // Rebalance the network to generate htlc in the two directions
8851         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8852
8853         // Route a HTLC from node 0 to node 1 (but don't settle)
8854         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8855
8856         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8857         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8858         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8859         let persister = test_utils::TestPersister::new();
8860         let watchtower_alice = {
8861                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8862                 let mut w = test_utils::TestVecWriter(Vec::new());
8863                 monitor.write(&mut w).unwrap();
8864                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8865                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8866                 assert!(new_monitor == *monitor);
8867                 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);
8868                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8869                 watchtower
8870         };
8871         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8872         let block = Block { header, txdata: vec![] };
8873         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8874         // transaction lock time requirements here.
8875         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));
8876         watchtower_alice.chain_monitor.block_connected(&block, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8877
8878         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8879         {
8880                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8881                 assert_eq!(txn.len(), 2);
8882                 txn.clear();
8883         }
8884
8885         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8886         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8887         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8888         let persister = test_utils::TestPersister::new();
8889         let watchtower_bob = {
8890                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8891                 let mut w = test_utils::TestVecWriter(Vec::new());
8892                 monitor.write(&mut w).unwrap();
8893                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8894                                 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8895                 assert!(new_monitor == *monitor);
8896                 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);
8897                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8898                 watchtower
8899         };
8900         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8901         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8902
8903         // Route another payment to generate another update with still previous HTLC pending
8904         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8905         {
8906                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8907         }
8908         check_added_monitors!(nodes[1], 1);
8909
8910         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8911         assert_eq!(updates.update_add_htlcs.len(), 1);
8912         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8913         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8914                 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8915                         // Watchtower Alice should already have seen the block and reject the update
8916                         if let Err(_) =  watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8917                         if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8918                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8919                 } else { assert!(false); }
8920         } else { assert!(false); };
8921         // Our local monitor is in-sync and hasn't processed yet timeout
8922         check_added_monitors!(nodes[0], 1);
8923
8924         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8925         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8926         watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8927
8928         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8929         let bob_state_y;
8930         {
8931                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8932                 assert_eq!(txn.len(), 2);
8933                 bob_state_y = txn[0].clone();
8934                 txn.clear();
8935         };
8936
8937         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8938         let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8939         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);
8940         {
8941                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8942                 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8943                 // the onchain detection of the HTLC output
8944                 assert_eq!(htlc_txn.len(), 2);
8945                 check_spends!(htlc_txn[0], bob_state_y);
8946                 check_spends!(htlc_txn[1], bob_state_y);
8947         }
8948 }
8949
8950 #[test]
8951 fn test_pre_lockin_no_chan_closed_update() {
8952         // Test that if a peer closes a channel in response to a funding_created message we don't
8953         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8954         // message).
8955         //
8956         // Doing so would imply a channel monitor update before the initial channel monitor
8957         // registration, violating our API guarantees.
8958         //
8959         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8960         // then opening a second channel with the same funding output as the first (which is not
8961         // rejected because the first channel does not exist in the ChannelManager) and closing it
8962         // before receiving funding_signed.
8963         let chanmon_cfgs = create_chanmon_cfgs(2);
8964         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8965         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8966         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8967
8968         // Create an initial channel
8969         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8970         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8971         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8972         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8973         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8974
8975         // Move the first channel through the funding flow...
8976         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8977
8978         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8979         check_added_monitors!(nodes[0], 0);
8980
8981         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8982         let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8983         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8984         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8985         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
8986 }
8987
8988 #[test]
8989 fn test_htlc_no_detection() {
8990         // This test is a mutation to underscore the detection logic bug we had
8991         // before #653. HTLC value routed is above the remaining balance, thus
8992         // inverting HTLC and `to_remote` output. HTLC will come second and
8993         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8994         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8995         // outputs order detection for correct spending children filtring.
8996
8997         let chanmon_cfgs = create_chanmon_cfgs(2);
8998         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8999         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9000         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9001
9002         // Create some initial channels
9003         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9004
9005         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
9006         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
9007         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
9008         assert_eq!(local_txn[0].input.len(), 1);
9009         assert_eq!(local_txn[0].output.len(), 3);
9010         check_spends!(local_txn[0], chan_1.3);
9011
9012         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
9013         let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
9014         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
9015         // We deliberately connect the local tx twice as this should provoke a failure calling
9016         // this test before #653 fix.
9017         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);
9018         check_closed_broadcast!(nodes[0], true);
9019         check_added_monitors!(nodes[0], 1);
9020         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
9021         connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
9022
9023         let htlc_timeout = {
9024                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9025                 assert_eq!(node_txn[1].input.len(), 1);
9026                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9027                 check_spends!(node_txn[1], local_txn[0]);
9028                 node_txn[1].clone()
9029         };
9030
9031         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
9032         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
9033         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
9034         expect_payment_failed!(nodes[0], our_payment_hash, true);
9035 }
9036
9037 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
9038         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
9039         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
9040         // Carol, Alice would be the upstream node, and Carol the downstream.)
9041         //
9042         // Steps of the test:
9043         // 1) Alice sends a HTLC to Carol through Bob.
9044         // 2) Carol doesn't settle the HTLC.
9045         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
9046         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
9047         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
9048         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
9049         // 5) Carol release the preimage to Bob off-chain.
9050         // 6) Bob claims the offered output on the broadcasted commitment.
9051         let chanmon_cfgs = create_chanmon_cfgs(3);
9052         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9053         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9054         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9055
9056         // Create some initial channels
9057         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9058         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9059
9060         // Steps (1) and (2):
9061         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
9062         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
9063
9064         // Check that Alice's commitment transaction now contains an output for this HTLC.
9065         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
9066         check_spends!(alice_txn[0], chan_ab.3);
9067         assert_eq!(alice_txn[0].output.len(), 2);
9068         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
9069         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9070         assert_eq!(alice_txn.len(), 2);
9071
9072         // Steps (3) and (4):
9073         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
9074         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
9075         let mut force_closing_node = 0; // Alice force-closes
9076         let mut counterparty_node = 1; // Bob if Alice force-closes
9077
9078         // Bob force-closes
9079         if !broadcast_alice {
9080                 force_closing_node = 1;
9081                 counterparty_node = 0;
9082         }
9083         nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
9084         check_closed_broadcast!(nodes[force_closing_node], true);
9085         check_added_monitors!(nodes[force_closing_node], 1);
9086         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
9087         if go_onchain_before_fulfill {
9088                 let txn_to_broadcast = match broadcast_alice {
9089                         true => alice_txn.clone(),
9090                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
9091                 };
9092                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
9093                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9094                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9095                 if broadcast_alice {
9096                         check_closed_broadcast!(nodes[1], true);
9097                         check_added_monitors!(nodes[1], 1);
9098                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9099                 }
9100                 assert_eq!(bob_txn.len(), 1);
9101                 check_spends!(bob_txn[0], chan_ab.3);
9102         }
9103
9104         // Step (5):
9105         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
9106         // process of removing the HTLC from their commitment transactions.
9107         nodes[2].node.claim_funds(payment_preimage);
9108         check_added_monitors!(nodes[2], 1);
9109         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
9110
9111         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
9112         assert!(carol_updates.update_add_htlcs.is_empty());
9113         assert!(carol_updates.update_fail_htlcs.is_empty());
9114         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
9115         assert!(carol_updates.update_fee.is_none());
9116         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
9117
9118         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
9119         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
9120         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
9121         if !go_onchain_before_fulfill && broadcast_alice {
9122                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9123                 assert_eq!(events.len(), 1);
9124                 match events[0] {
9125                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
9126                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9127                         },
9128                         _ => panic!("Unexpected event"),
9129                 };
9130         }
9131         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
9132         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
9133         // Carol<->Bob's updated commitment transaction info.
9134         check_added_monitors!(nodes[1], 2);
9135
9136         let events = nodes[1].node.get_and_clear_pending_msg_events();
9137         assert_eq!(events.len(), 2);
9138         let bob_revocation = match events[0] {
9139                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9140                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9141                         (*msg).clone()
9142                 },
9143                 _ => panic!("Unexpected event"),
9144         };
9145         let bob_updates = match events[1] {
9146                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
9147                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9148                         (*updates).clone()
9149                 },
9150                 _ => panic!("Unexpected event"),
9151         };
9152
9153         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
9154         check_added_monitors!(nodes[2], 1);
9155         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
9156         check_added_monitors!(nodes[2], 1);
9157
9158         let events = nodes[2].node.get_and_clear_pending_msg_events();
9159         assert_eq!(events.len(), 1);
9160         let carol_revocation = match events[0] {
9161                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9162                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
9163                         (*msg).clone()
9164                 },
9165                 _ => panic!("Unexpected event"),
9166         };
9167         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
9168         check_added_monitors!(nodes[1], 1);
9169
9170         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
9171         // here's where we put said channel's commitment tx on-chain.
9172         let mut txn_to_broadcast = alice_txn.clone();
9173         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
9174         if !go_onchain_before_fulfill {
9175                 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
9176                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9177                 // If Bob was the one to force-close, he will have already passed these checks earlier.
9178                 if broadcast_alice {
9179                         check_closed_broadcast!(nodes[1], true);
9180                         check_added_monitors!(nodes[1], 1);
9181                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9182                 }
9183                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9184                 if broadcast_alice {
9185                         // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
9186                         // new block being connected. The ChannelManager being notified triggers a monitor update,
9187                         // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
9188                         // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
9189                         // broadcasted.
9190                         assert_eq!(bob_txn.len(), 3);
9191                         check_spends!(bob_txn[1], chan_ab.3);
9192                 } else {
9193                         assert_eq!(bob_txn.len(), 2);
9194                         check_spends!(bob_txn[0], chan_ab.3);
9195                 }
9196         }
9197
9198         // Step (6):
9199         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
9200         // broadcasted commitment transaction.
9201         {
9202                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9203                 if go_onchain_before_fulfill {
9204                         // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
9205                         assert_eq!(bob_txn.len(), 2);
9206                 }
9207                 let script_weight = match broadcast_alice {
9208                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
9209                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
9210                 };
9211                 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
9212                 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
9213                 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
9214                 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
9215                 if broadcast_alice && !go_onchain_before_fulfill {
9216                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
9217                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
9218                 } else {
9219                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
9220                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
9221                 }
9222         }
9223 }
9224
9225 #[test]
9226 fn test_onchain_htlc_settlement_after_close() {
9227         do_test_onchain_htlc_settlement_after_close(true, true);
9228         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
9229         do_test_onchain_htlc_settlement_after_close(true, false);
9230         do_test_onchain_htlc_settlement_after_close(false, false);
9231 }
9232
9233 #[test]
9234 fn test_duplicate_chan_id() {
9235         // Test that if a given peer tries to open a channel with the same channel_id as one that is
9236         // already open we reject it and keep the old channel.
9237         //
9238         // Previously, full_stack_target managed to figure out that if you tried to open two channels
9239         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
9240         // the existing channel when we detect the duplicate new channel, screwing up our monitor
9241         // updating logic for the existing channel.
9242         let chanmon_cfgs = create_chanmon_cfgs(2);
9243         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9244         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9245         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9246
9247         // Create an initial channel
9248         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9249         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9250         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9251         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()));
9252
9253         // Try to create a second channel with the same temporary_channel_id as the first and check
9254         // that it is rejected.
9255         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9256         {
9257                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9258                 assert_eq!(events.len(), 1);
9259                 match events[0] {
9260                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9261                                 // Technically, at this point, nodes[1] would be justified in thinking both the
9262                                 // first (valid) and second (invalid) channels are closed, given they both have
9263                                 // the same non-temporary channel_id. However, currently we do not, so we just
9264                                 // move forward with it.
9265                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9266                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9267                         },
9268                         _ => panic!("Unexpected event"),
9269                 }
9270         }
9271
9272         // Move the first channel through the funding flow...
9273         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9274
9275         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9276         check_added_monitors!(nodes[0], 0);
9277
9278         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9279         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9280         {
9281                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9282                 assert_eq!(added_monitors.len(), 1);
9283                 assert_eq!(added_monitors[0].0, funding_output);
9284                 added_monitors.clear();
9285         }
9286         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9287
9288         let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9289         let channel_id = funding_outpoint.to_channel_id();
9290
9291         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9292         // temporary one).
9293
9294         // First try to open a second channel with a temporary channel id equal to the txid-based one.
9295         // Technically this is allowed by the spec, but we don't support it and there's little reason
9296         // to. Still, it shouldn't cause any other issues.
9297         open_chan_msg.temporary_channel_id = channel_id;
9298         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9299         {
9300                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9301                 assert_eq!(events.len(), 1);
9302                 match events[0] {
9303                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9304                                 // Technically, at this point, nodes[1] would be justified in thinking both
9305                                 // channels are closed, but currently we do not, so we just move forward with it.
9306                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9307                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9308                         },
9309                         _ => panic!("Unexpected event"),
9310                 }
9311         }
9312
9313         // Now try to create a second channel which has a duplicate funding output.
9314         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9315         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9316         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
9317         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()));
9318         create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
9319
9320         let funding_created = {
9321                 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
9322                 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
9323                 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
9324                 // try to create another channel. Instead, we drop the channel entirely here (leaving the
9325                 // channelmanager in a possibly nonsense state instead).
9326                 let mut as_chan = a_channel_lock.by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
9327                 let logger = test_utils::TestLogger::new();
9328                 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
9329         };
9330         check_added_monitors!(nodes[0], 0);
9331         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9332         // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
9333         // still needs to be cleared here.
9334         check_added_monitors!(nodes[1], 1);
9335
9336         // ...still, nodes[1] will reject the duplicate channel.
9337         {
9338                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9339                 assert_eq!(events.len(), 1);
9340                 match events[0] {
9341                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9342                                 // Technically, at this point, nodes[1] would be justified in thinking both
9343                                 // channels are closed, but currently we do not, so we just move forward with it.
9344                                 assert_eq!(msg.channel_id, channel_id);
9345                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9346                         },
9347                         _ => panic!("Unexpected event"),
9348                 }
9349         }
9350
9351         // finally, finish creating the original channel and send a payment over it to make sure
9352         // everything is functional.
9353         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9354         {
9355                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9356                 assert_eq!(added_monitors.len(), 1);
9357                 assert_eq!(added_monitors[0].0, funding_output);
9358                 added_monitors.clear();
9359         }
9360
9361         let events_4 = nodes[0].node.get_and_clear_pending_events();
9362         assert_eq!(events_4.len(), 0);
9363         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9364         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9365
9366         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9367         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9368         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9369         send_payment(&nodes[0], &[&nodes[1]], 8000000);
9370 }
9371
9372 #[test]
9373 fn test_error_chans_closed() {
9374         // Test that we properly handle error messages, closing appropriate channels.
9375         //
9376         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9377         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9378         // we can test various edge cases around it to ensure we don't regress.
9379         let chanmon_cfgs = create_chanmon_cfgs(3);
9380         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9381         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9382         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9383
9384         // Create some initial channels
9385         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9386         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9387         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9388
9389         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9390         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9391         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9392
9393         // Closing a channel from a different peer has no effect
9394         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9395         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9396
9397         // Closing one channel doesn't impact others
9398         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9399         check_added_monitors!(nodes[0], 1);
9400         check_closed_broadcast!(nodes[0], false);
9401         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9402         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9403         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9404         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);
9405         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);
9406
9407         // A null channel ID should close all channels
9408         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9409         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9410         check_added_monitors!(nodes[0], 2);
9411         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9412         let events = nodes[0].node.get_and_clear_pending_msg_events();
9413         assert_eq!(events.len(), 2);
9414         match events[0] {
9415                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9416                         assert_eq!(msg.contents.flags & 2, 2);
9417                 },
9418                 _ => panic!("Unexpected event"),
9419         }
9420         match events[1] {
9421                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9422                         assert_eq!(msg.contents.flags & 2, 2);
9423                 },
9424                 _ => panic!("Unexpected event"),
9425         }
9426         // Note that at this point users of a standard PeerHandler will end up calling
9427         // peer_disconnected with no_connection_possible set to false, duplicating the
9428         // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
9429         // users with their own peer handling logic. We duplicate the call here, however.
9430         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9431         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9432
9433         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
9434         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9435         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9436 }
9437
9438 #[test]
9439 fn test_invalid_funding_tx() {
9440         // Test that we properly handle invalid funding transactions sent to us from a peer.
9441         //
9442         // Previously, all other major lightning implementations had failed to properly sanitize
9443         // funding transactions from their counterparties, leading to a multi-implementation critical
9444         // security vulnerability (though we always sanitized properly, we've previously had
9445         // un-released crashes in the sanitization process).
9446         //
9447         // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9448         // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9449         // gave up on it. We test this here by generating such a transaction.
9450         let chanmon_cfgs = create_chanmon_cfgs(2);
9451         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9452         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9453         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9454
9455         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9456         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()));
9457         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()));
9458
9459         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9460
9461         // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9462         // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9463         // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9464         // its length.
9465         let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9466         assert!(chan_utils::HTLCType::scriptlen_to_htlctype(wit_program.len()).unwrap() ==
9467                 chan_utils::HTLCType::AcceptedHTLC);
9468
9469         let wit_program_script: Script = wit_program.clone().into();
9470         for output in tx.output.iter_mut() {
9471                 // Make the confirmed funding transaction have a bogus script_pubkey
9472                 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9473         }
9474
9475         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9476         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()));
9477         check_added_monitors!(nodes[1], 1);
9478
9479         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()));
9480         check_added_monitors!(nodes[0], 1);
9481
9482         let events_1 = nodes[0].node.get_and_clear_pending_events();
9483         assert_eq!(events_1.len(), 0);
9484
9485         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9486         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9487         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9488
9489         let expected_err = "funding tx had wrong script/value or output index";
9490         confirm_transaction_at(&nodes[1], &tx, 1);
9491         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9492         check_added_monitors!(nodes[1], 1);
9493         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9494         assert_eq!(events_2.len(), 1);
9495         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9496                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9497                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9498                         assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9499                 } else { panic!(); }
9500         } else { panic!(); }
9501         assert_eq!(nodes[1].node.list_channels().len(), 0);
9502
9503         // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9504         // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9505         // as its not 32 bytes long.
9506         let mut spend_tx = Transaction {
9507                 version: 2i32, lock_time: PackedLockTime::ZERO,
9508                 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9509                         previous_output: BitcoinOutPoint {
9510                                 txid: tx.txid(),
9511                                 vout: idx as u32,
9512                         },
9513                         script_sig: Script::new(),
9514                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9515                         witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9516                 }).collect(),
9517                 output: vec![TxOut {
9518                         value: 1000,
9519                         script_pubkey: Script::new(),
9520                 }]
9521         };
9522         check_spends!(spend_tx, tx);
9523         mine_transaction(&nodes[1], &spend_tx);
9524 }
9525
9526 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9527         // In the first version of the chain::Confirm interface, after a refactor was made to not
9528         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9529         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9530         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9531         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9532         // spending transaction until height N+1 (or greater). This was due to the way
9533         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9534         // spending transaction at the height the input transaction was confirmed at, not whether we
9535         // should broadcast a spending transaction at the current height.
9536         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9537         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9538         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9539         // until we learned about an additional block.
9540         //
9541         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9542         // aren't broadcasting transactions too early (ie not broadcasting them at all).
9543         let chanmon_cfgs = create_chanmon_cfgs(3);
9544         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9545         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9546         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9547         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9548
9549         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
9550         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
9551         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9552         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9553         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9554
9555         nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9556         check_closed_broadcast!(nodes[1], true);
9557         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9558         check_added_monitors!(nodes[1], 1);
9559         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9560         assert_eq!(node_txn.len(), 1);
9561
9562         let conf_height = nodes[1].best_block_info().1;
9563         if !test_height_before_timelock {
9564                 connect_blocks(&nodes[1], 24 * 6);
9565         }
9566         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9567                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9568         if test_height_before_timelock {
9569                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9570                 // generate any events or broadcast any transactions
9571                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9572                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9573         } else {
9574                 // We should broadcast an HTLC transaction spending our funding transaction first
9575                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9576                 assert_eq!(spending_txn.len(), 2);
9577                 assert_eq!(spending_txn[0], node_txn[0]);
9578                 check_spends!(spending_txn[1], node_txn[0]);
9579                 // We should also generate a SpendableOutputs event with the to_self output (as its
9580                 // timelock is up).
9581                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9582                 assert_eq!(descriptor_spend_txn.len(), 1);
9583
9584                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9585                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9586                 // additional block built on top of the current chain.
9587                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9588                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9589                 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 }]);
9590                 check_added_monitors!(nodes[1], 1);
9591
9592                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9593                 assert!(updates.update_add_htlcs.is_empty());
9594                 assert!(updates.update_fulfill_htlcs.is_empty());
9595                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9596                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9597                 assert!(updates.update_fee.is_none());
9598                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9599                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9600                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9601         }
9602 }
9603
9604 #[test]
9605 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9606         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9607         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9608 }
9609
9610 #[test]
9611 fn test_forwardable_regen() {
9612         // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
9613         // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
9614         // HTLCs.
9615         // We test it for both payment receipt and payment forwarding.
9616
9617         let chanmon_cfgs = create_chanmon_cfgs(3);
9618         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9619         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9620         let persister: test_utils::TestPersister;
9621         let new_chain_monitor: test_utils::TestChainMonitor;
9622         let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9623         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9624         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
9625         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known()).2;
9626
9627         // First send a payment to nodes[1]
9628         let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
9629         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9630         check_added_monitors!(nodes[0], 1);
9631
9632         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9633         assert_eq!(events.len(), 1);
9634         let payment_event = SendEvent::from_event(events.pop().unwrap());
9635         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9636         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9637
9638         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9639
9640         // Next send a payment which is forwarded by nodes[1]
9641         let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
9642         nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
9643         check_added_monitors!(nodes[0], 1);
9644
9645         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9646         assert_eq!(events.len(), 1);
9647         let payment_event = SendEvent::from_event(events.pop().unwrap());
9648         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9649         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9650
9651         // There is already a PendingHTLCsForwardable event "pending" so another one will not be
9652         // generated
9653         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
9654
9655         // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
9656         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9657         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9658
9659         let nodes_1_serialized = nodes[1].node.encode();
9660         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9661         let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9662         get_monitor!(nodes[1], chan_id_1).write(&mut chan_0_monitor_serialized).unwrap();
9663         get_monitor!(nodes[1], chan_id_2).write(&mut chan_1_monitor_serialized).unwrap();
9664
9665         persister = test_utils::TestPersister::new();
9666         let keys_manager = &chanmon_cfgs[1].keys_manager;
9667         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);
9668         nodes[1].chain_monitor = &new_chain_monitor;
9669
9670         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
9671         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9672                 &mut chan_0_monitor_read, keys_manager).unwrap();
9673         assert!(chan_0_monitor_read.is_empty());
9674         let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
9675         let (_, mut chan_1_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9676                 &mut chan_1_monitor_read, keys_manager).unwrap();
9677         assert!(chan_1_monitor_read.is_empty());
9678
9679         let mut nodes_1_read = &nodes_1_serialized[..];
9680         let (_, nodes_1_deserialized_tmp) = {
9681                 let mut channel_monitors = HashMap::new();
9682                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
9683                 channel_monitors.insert(chan_1_monitor.get_funding_txo().0, &mut chan_1_monitor);
9684                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
9685                         default_config: UserConfig::default(),
9686                         keys_manager,
9687                         fee_estimator: node_cfgs[1].fee_estimator,
9688                         chain_monitor: nodes[1].chain_monitor,
9689                         tx_broadcaster: nodes[1].tx_broadcaster.clone(),
9690                         logger: nodes[1].logger,
9691                         channel_monitors,
9692                 }).unwrap()
9693         };
9694         nodes_1_deserialized = nodes_1_deserialized_tmp;
9695         assert!(nodes_1_read.is_empty());
9696
9697         assert!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
9698         assert!(nodes[1].chain_monitor.watch_channel(chan_1_monitor.get_funding_txo().0, chan_1_monitor).is_ok());
9699         nodes[1].node = &nodes_1_deserialized;
9700         check_added_monitors!(nodes[1], 2);
9701
9702         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9703         // Note that nodes[1] and nodes[2] resend their channel_ready here since they haven't updated
9704         // the commitment state.
9705         reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9706
9707         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9708
9709         expect_pending_htlcs_forwardable!(nodes[1]);
9710         expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
9711         check_added_monitors!(nodes[1], 1);
9712
9713         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9714         assert_eq!(events.len(), 1);
9715         let payment_event = SendEvent::from_event(events.pop().unwrap());
9716         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9717         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
9718         expect_pending_htlcs_forwardable!(nodes[2]);
9719         expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
9720
9721         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
9722         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
9723 }
9724
9725 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9726         let chanmon_cfgs = create_chanmon_cfgs(2);
9727         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9728         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9729         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9730
9731         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9732
9733         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
9734                 .with_features(InvoiceFeatures::known());
9735         let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
9736
9737         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9738
9739         {
9740                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9741                 check_added_monitors!(nodes[0], 1);
9742                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9743                 assert_eq!(events.len(), 1);
9744                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9745                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9746                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9747         }
9748         expect_pending_htlcs_forwardable!(nodes[1]);
9749         expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9750
9751         {
9752                 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9753                 check_added_monitors!(nodes[0], 1);
9754                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9755                 assert_eq!(events.len(), 1);
9756                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9757                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9758                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9759                 // At this point, nodes[1] would notice it has too much value for the payment. It will
9760                 // assume the second is a privacy attack (no longer particularly relevant
9761                 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9762                 // the first HTLC delivered above.
9763         }
9764
9765         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9766         nodes[1].node.process_pending_htlc_forwards();
9767
9768         if test_for_second_fail_panic {
9769                 // Now we go fail back the first HTLC from the user end.
9770                 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9771
9772                 let expected_destinations = vec![
9773                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9774                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9775                 ];
9776                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],  expected_destinations);
9777                 nodes[1].node.process_pending_htlc_forwards();
9778
9779                 check_added_monitors!(nodes[1], 1);
9780                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9781                 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9782
9783                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9784                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9785                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9786
9787                 let failure_events = nodes[0].node.get_and_clear_pending_events();
9788                 assert_eq!(failure_events.len(), 2);
9789                 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9790                 if let Event::PaymentPathFailed { .. } = failure_events[1] {} else { panic!(); }
9791         } else {
9792                 // Let the second HTLC fail and claim the first
9793                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9794                 nodes[1].node.process_pending_htlc_forwards();
9795
9796                 check_added_monitors!(nodes[1], 1);
9797                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9798                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9799                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9800
9801                 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9802
9803                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9804         }
9805 }
9806
9807 #[test]
9808 fn test_dup_htlc_second_fail_panic() {
9809         // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9810         // value for the payment, we'd fail back both HTLCs after generating a `PaymentReceived` event.
9811         // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9812         // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9813         do_test_dup_htlc_second_rejected(true);
9814 }
9815
9816 #[test]
9817 fn test_dup_htlc_second_rejected() {
9818         // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9819         // simply reject the second HTLC but are still able to claim the first HTLC.
9820         do_test_dup_htlc_second_rejected(false);
9821 }
9822
9823 #[test]
9824 fn test_inconsistent_mpp_params() {
9825         // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9826         // such HTLC and allow the second to stay.
9827         let chanmon_cfgs = create_chanmon_cfgs(4);
9828         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9829         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9830         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9831
9832         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9833         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9834         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9835         let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9836
9837         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
9838                 .with_features(InvoiceFeatures::known());
9839         let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
9840         assert_eq!(route.paths.len(), 2);
9841         route.paths.sort_by(|path_a, _| {
9842                 // Sort the path so that the path through nodes[1] comes first
9843                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9844                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9845         });
9846         let payment_params_opt = Some(payment_params);
9847
9848         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9849
9850         let cur_height = nodes[0].best_block_info().1;
9851         let payment_id = PaymentId([42; 32]);
9852         {
9853                 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();
9854                 check_added_monitors!(nodes[0], 1);
9855
9856                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9857                 assert_eq!(events.len(), 1);
9858                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9859         }
9860         assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9861
9862         {
9863                 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();
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                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9869
9870                 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9871                 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9872
9873                 expect_pending_htlcs_forwardable!(nodes[2]);
9874                 check_added_monitors!(nodes[2], 1);
9875
9876                 let mut events = nodes[2].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[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9881                 check_added_monitors!(nodes[3], 0);
9882                 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9883
9884                 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9885                 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9886                 // post-payment_secrets) and fail back the new HTLC.
9887         }
9888         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9889         nodes[3].node.process_pending_htlc_forwards();
9890         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9891         nodes[3].node.process_pending_htlc_forwards();
9892
9893         check_added_monitors!(nodes[3], 1);
9894
9895         let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9896         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9897         commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9898
9899         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 }]);
9900         check_added_monitors!(nodes[2], 1);
9901
9902         let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9903         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9904         commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9905
9906         expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9907
9908         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();
9909         check_added_monitors!(nodes[0], 1);
9910
9911         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9912         assert_eq!(events.len(), 1);
9913         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9914
9915         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9916 }
9917
9918 #[test]
9919 fn test_keysend_payments_to_public_node() {
9920         let chanmon_cfgs = create_chanmon_cfgs(2);
9921         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9922         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9923         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9924
9925         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9926         let network_graph = nodes[0].network_graph;
9927         let payer_pubkey = nodes[0].node.get_our_node_id();
9928         let payee_pubkey = nodes[1].node.get_our_node_id();
9929         let route_params = RouteParameters {
9930                 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9931                 final_value_msat: 10000,
9932                 final_cltv_expiry_delta: 40,
9933         };
9934         let scorer = test_utils::TestScorer::with_penalty(0);
9935         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9936         let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9937
9938         let test_preimage = PaymentPreimage([42; 32]);
9939         let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9940         check_added_monitors!(nodes[0], 1);
9941         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9942         assert_eq!(events.len(), 1);
9943         let event = events.pop().unwrap();
9944         let path = vec![&nodes[1]];
9945         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9946         claim_payment(&nodes[0], &path, test_preimage);
9947 }
9948
9949 #[test]
9950 fn test_keysend_payments_to_private_node() {
9951         let chanmon_cfgs = create_chanmon_cfgs(2);
9952         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9953         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9954         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9955
9956         let payer_pubkey = nodes[0].node.get_our_node_id();
9957         let payee_pubkey = nodes[1].node.get_our_node_id();
9958         nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9959         nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9960
9961         let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
9962         let route_params = RouteParameters {
9963                 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9964                 final_value_msat: 10000,
9965                 final_cltv_expiry_delta: 40,
9966         };
9967         let network_graph = nodes[0].network_graph;
9968         let first_hops = nodes[0].node.list_usable_channels();
9969         let scorer = test_utils::TestScorer::with_penalty(0);
9970         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9971         let route = find_route(
9972                 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9973                 nodes[0].logger, &scorer, &random_seed_bytes
9974         ).unwrap();
9975
9976         let test_preimage = PaymentPreimage([42; 32]);
9977         let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9978         check_added_monitors!(nodes[0], 1);
9979         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9980         assert_eq!(events.len(), 1);
9981         let event = events.pop().unwrap();
9982         let path = vec![&nodes[1]];
9983         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9984         claim_payment(&nodes[0], &path, test_preimage);
9985 }
9986
9987 #[test]
9988 fn test_double_partial_claim() {
9989         // Test what happens if a node receives a payment, generates a PaymentReceived event, the HTLCs
9990         // time out, the sender resends only some of the MPP parts, then the user processes the
9991         // PaymentReceived event, ensuring they don't inadvertently claim only part of the full payment
9992         // amount.
9993         let chanmon_cfgs = create_chanmon_cfgs(4);
9994         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9995         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9996         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9997
9998         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9999         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
10000         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
10001         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
10002
10003         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
10004         assert_eq!(route.paths.len(), 2);
10005         route.paths.sort_by(|path_a, _| {
10006                 // Sort the path so that the path through nodes[1] comes first
10007                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
10008                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
10009         });
10010
10011         send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
10012         // nodes[3] has now received a PaymentReceived event...which it will take some (exorbitant)
10013         // amount of time to respond to.
10014
10015         // Connect some blocks to time out the payment
10016         connect_blocks(&nodes[3], TEST_FINAL_CLTV);
10017         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
10018
10019         let failed_destinations = vec![
10020                 HTLCDestination::FailedPayment { payment_hash },
10021                 HTLCDestination::FailedPayment { payment_hash },
10022         ];
10023         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
10024
10025         pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
10026
10027         // nodes[1] now retries one of the two paths...
10028         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10029         check_added_monitors!(nodes[0], 2);
10030
10031         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10032         assert_eq!(events.len(), 2);
10033         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
10034
10035         // At this point nodes[3] has received one half of the payment, and the user goes to handle
10036         // that PaymentReceived event they got hours ago and never handled...we should refuse to claim.
10037         nodes[3].node.claim_funds(payment_preimage);
10038         check_added_monitors!(nodes[3], 0);
10039         assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
10040 }
10041
10042 fn do_test_partial_claim_before_restart(persist_both_monitors: bool) {
10043         // Test what happens if a node receives an MPP payment, claims it, but crashes before
10044         // persisting the ChannelManager. If `persist_both_monitors` is false, also crash after only
10045         // updating one of the two channels' ChannelMonitors. As a result, on startup, we'll (a) still
10046         // have the PaymentReceived event, (b) have one (or two) channel(s) that goes on chain with the
10047         // HTLC preimage in them, and (c) optionally have one channel that is live off-chain but does
10048         // not have the preimage tied to the still-pending HTLC.
10049         //
10050         // To get to the correct state, on startup we should propagate the preimage to the
10051         // still-off-chain channel, claiming the HTLC as soon as the peer connects, with the monitor
10052         // receiving the preimage without a state update.
10053         //
10054         // Further, we should generate a `PaymentClaimed` event to inform the user that the payment was
10055         // definitely claimed.
10056         let chanmon_cfgs = create_chanmon_cfgs(4);
10057         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
10058         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
10059
10060         let persister: test_utils::TestPersister;
10061         let new_chain_monitor: test_utils::TestChainMonitor;
10062         let nodes_3_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
10063
10064         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
10065
10066         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
10067         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
10068         let chan_id_persisted = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known()).2;
10069         let chan_id_not_persisted = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known()).2;
10070
10071         // Create an MPP route for 15k sats, more than the default htlc-max of 10%
10072         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
10073         assert_eq!(route.paths.len(), 2);
10074         route.paths.sort_by(|path_a, _| {
10075                 // Sort the path so that the path through nodes[1] comes first
10076                 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
10077                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
10078         });
10079
10080         nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10081         check_added_monitors!(nodes[0], 2);
10082
10083         // Send the payment through to nodes[3] *without* clearing the PaymentReceived event
10084         let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
10085         assert_eq!(send_events.len(), 2);
10086         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);
10087         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);
10088
10089         // Now that we have an MPP payment pending, get the latest encoded copies of nodes[3]'s
10090         // monitors and ChannelManager, for use later, if we don't want to persist both monitors.
10091         let mut original_monitor = test_utils::TestVecWriter(Vec::new());
10092         if !persist_both_monitors {
10093                 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10094                         if outpoint.to_channel_id() == chan_id_not_persisted {
10095                                 assert!(original_monitor.0.is_empty());
10096                                 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
10097                         }
10098                 }
10099         }
10100
10101         let mut original_manager = test_utils::TestVecWriter(Vec::new());
10102         nodes[3].node.write(&mut original_manager).unwrap();
10103
10104         expect_payment_received!(nodes[3], payment_hash, payment_secret, 15_000_000);
10105
10106         nodes[3].node.claim_funds(payment_preimage);
10107         check_added_monitors!(nodes[3], 2);
10108         expect_payment_claimed!(nodes[3], payment_hash, 15_000_000);
10109
10110         // Now fetch one of the two updated ChannelMonitors from nodes[3], and restart pretending we
10111         // crashed in between the two persistence calls - using one old ChannelMonitor and one new one,
10112         // with the old ChannelManager.
10113         let mut updated_monitor = test_utils::TestVecWriter(Vec::new());
10114         for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10115                 if outpoint.to_channel_id() == chan_id_persisted {
10116                         assert!(updated_monitor.0.is_empty());
10117                         nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut updated_monitor).unwrap();
10118                 }
10119         }
10120         // If `persist_both_monitors` is set, get the second monitor here as well
10121         if persist_both_monitors {
10122                 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10123                         if outpoint.to_channel_id() == chan_id_not_persisted {
10124                                 assert!(original_monitor.0.is_empty());
10125                                 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
10126                         }
10127                 }
10128         }
10129
10130         // Now restart nodes[3].
10131         persister = test_utils::TestPersister::new();
10132         let keys_manager = &chanmon_cfgs[3].keys_manager;
10133         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);
10134         nodes[3].chain_monitor = &new_chain_monitor;
10135         let mut monitors = Vec::new();
10136         for mut monitor_data in [original_monitor, updated_monitor].iter() {
10137                 let (_, mut deserialized_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut &monitor_data.0[..], keys_manager).unwrap();
10138                 monitors.push(deserialized_monitor);
10139         }
10140
10141         let config = UserConfig::default();
10142         nodes_3_deserialized = {
10143                 let mut channel_monitors = HashMap::new();
10144                 for monitor in monitors.iter_mut() {
10145                         channel_monitors.insert(monitor.get_funding_txo().0, monitor);
10146                 }
10147                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut &original_manager.0[..], ChannelManagerReadArgs {
10148                         default_config: config,
10149                         keys_manager,
10150                         fee_estimator: node_cfgs[3].fee_estimator,
10151                         chain_monitor: nodes[3].chain_monitor,
10152                         tx_broadcaster: nodes[3].tx_broadcaster.clone(),
10153                         logger: nodes[3].logger,
10154                         channel_monitors,
10155                 }).unwrap().1
10156         };
10157         nodes[3].node = &nodes_3_deserialized;
10158
10159         for monitor in monitors {
10160                 // On startup the preimage should have been copied into the non-persisted monitor:
10161                 assert!(monitor.get_stored_preimages().contains_key(&payment_hash));
10162                 nodes[3].chain_monitor.watch_channel(monitor.get_funding_txo().0.clone(), monitor).unwrap();
10163         }
10164         check_added_monitors!(nodes[3], 2);
10165
10166         nodes[1].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
10167         nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
10168
10169         // During deserialization, we should have closed one channel and broadcast its latest
10170         // commitment transaction. We should also still have the original PaymentReceived event we
10171         // never finished processing.
10172         let events = nodes[3].node.get_and_clear_pending_events();
10173         assert_eq!(events.len(), if persist_both_monitors { 4 } else { 3 });
10174         if let Event::PaymentReceived { amount_msat: 15_000_000, .. } = events[0] { } else { panic!(); }
10175         if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[1] { } else { panic!(); }
10176         if persist_both_monitors {
10177                 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[2] { } else { panic!(); }
10178         }
10179
10180         // On restart, we should also get a duplicate PaymentClaimed event as we persisted the
10181         // ChannelManager prior to handling the original one.
10182         if let Event::PaymentClaimed { payment_hash: our_payment_hash, amount_msat: 15_000_000, .. } =
10183                 events[if persist_both_monitors { 3 } else { 2 }]
10184         {
10185                 assert_eq!(payment_hash, our_payment_hash);
10186         } else { panic!(); }
10187
10188         assert_eq!(nodes[3].node.list_channels().len(), if persist_both_monitors { 0 } else { 1 });
10189         if !persist_both_monitors {
10190                 // If one of the two channels is still live, reveal the payment preimage over it.
10191
10192                 nodes[3].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
10193                 let reestablish_1 = get_chan_reestablish_msgs!(nodes[3], nodes[2]);
10194                 nodes[2].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
10195                 let reestablish_2 = get_chan_reestablish_msgs!(nodes[2], nodes[3]);
10196
10197                 nodes[2].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish_1[0]);
10198                 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[3].node.get_our_node_id());
10199                 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
10200
10201                 nodes[3].node.handle_channel_reestablish(&nodes[2].node.get_our_node_id(), &reestablish_2[0]);
10202
10203                 // Once we call `get_and_clear_pending_msg_events` the holding cell is cleared and the HTLC
10204                 // claim should fly.
10205                 let ds_msgs = nodes[3].node.get_and_clear_pending_msg_events();
10206                 check_added_monitors!(nodes[3], 1);
10207                 assert_eq!(ds_msgs.len(), 2);
10208                 if let MessageSendEvent::SendChannelUpdate { .. } = ds_msgs[1] {} else { panic!(); }
10209
10210                 let cs_updates = match ds_msgs[0] {
10211                         MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
10212                                 nodes[2].node.handle_update_fulfill_htlc(&nodes[3].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
10213                                 check_added_monitors!(nodes[2], 1);
10214                                 let cs_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
10215                                 expect_payment_forwarded!(nodes[2], nodes[0], nodes[3], Some(1000), false, false);
10216                                 commitment_signed_dance!(nodes[2], nodes[3], updates.commitment_signed, false, true);
10217                                 cs_updates
10218                         }
10219                         _ => panic!(),
10220                 };
10221
10222                 nodes[0].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &cs_updates.update_fulfill_htlcs[0]);
10223                 commitment_signed_dance!(nodes[0], nodes[2], cs_updates.commitment_signed, false, true);
10224                 expect_payment_sent!(nodes[0], payment_preimage);
10225         }
10226 }
10227
10228 #[test]
10229 fn test_partial_claim_before_restart() {
10230         do_test_partial_claim_before_restart(false);
10231         do_test_partial_claim_before_restart(true);
10232 }
10233
10234 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
10235 #[derive(Clone, Copy, PartialEq)]
10236 enum ExposureEvent {
10237         /// Breach occurs at HTLC forwarding (see `send_htlc`)
10238         AtHTLCForward,
10239         /// Breach occurs at HTLC reception (see `update_add_htlc`)
10240         AtHTLCReception,
10241         /// Breach occurs at outbound update_fee (see `send_update_fee`)
10242         AtUpdateFeeOutbound,
10243 }
10244
10245 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
10246         // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
10247         // policy.
10248         //
10249         // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
10250         // trimmed-to-dust HTLC outbound balance and this new payment as included on next
10251         // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
10252         // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
10253         // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
10254         // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
10255         // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
10256         // might be available again for HTLC processing once the dust bandwidth has cleared up.
10257
10258         let chanmon_cfgs = create_chanmon_cfgs(2);
10259         let mut config = test_default_channel_config();
10260         config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
10261         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10262         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
10263         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10264
10265         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
10266         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10267         open_channel.max_htlc_value_in_flight_msat = 50_000_000;
10268         open_channel.max_accepted_htlcs = 60;
10269         if on_holder_tx {
10270                 open_channel.dust_limit_satoshis = 546;
10271         }
10272         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
10273         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10274         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
10275
10276         let opt_anchors = false;
10277
10278         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
10279
10280         if on_holder_tx {
10281                 if let Some(mut chan) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&temporary_channel_id) {
10282                         chan.holder_dust_limit_satoshis = 546;
10283                 }
10284         }
10285
10286         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
10287         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()));
10288         check_added_monitors!(nodes[1], 1);
10289
10290         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()));
10291         check_added_monitors!(nodes[0], 1);
10292
10293         let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
10294         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
10295         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
10296
10297         let dust_buffer_feerate = {
10298                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
10299                 let chan = chan_lock.by_id.get(&channel_id).unwrap();
10300                 chan.get_dust_buffer_feerate(None) as u64
10301         };
10302         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;
10303         let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
10304
10305         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;
10306         let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
10307
10308         let dust_htlc_on_counterparty_tx: u64 = 25;
10309         let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
10310
10311         if on_holder_tx {
10312                 if dust_outbound_balance {
10313                         // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10314                         // Outbound dust balance: 4372 sats
10315                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
10316                         for i in 0..dust_outbound_htlc_on_holder_tx {
10317                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
10318                                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
10319                         }
10320                 } else {
10321                         // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10322                         // Inbound dust balance: 4372 sats
10323                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
10324                         for _ in 0..dust_inbound_htlc_on_holder_tx {
10325                                 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
10326                         }
10327                 }
10328         } else {
10329                 if dust_outbound_balance {
10330                         // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10331                         // Outbound dust balance: 5000 sats
10332                         for i in 0..dust_htlc_on_counterparty_tx {
10333                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
10334                                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
10335                         }
10336                 } else {
10337                         // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10338                         // Inbound dust balance: 5000 sats
10339                         for _ in 0..dust_htlc_on_counterparty_tx {
10340                                 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
10341                         }
10342                 }
10343         }
10344
10345         let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
10346         if exposure_breach_event == ExposureEvent::AtHTLCForward {
10347                 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 });
10348                 let mut config = UserConfig::default();
10349                 // With default dust exposure: 5000 sats
10350                 if on_holder_tx {
10351                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
10352                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
10353                         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)));
10354                 } else {
10355                         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)));
10356                 }
10357         } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
10358                 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 });
10359                 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10360                 check_added_monitors!(nodes[1], 1);
10361                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
10362                 assert_eq!(events.len(), 1);
10363                 let payment_event = SendEvent::from_event(events.remove(0));
10364                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
10365                 // With default dust exposure: 5000 sats
10366                 if on_holder_tx {
10367                         // Outbound dust balance: 6399 sats
10368                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
10369                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
10370                         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);
10371                 } else {
10372                         // Outbound dust balance: 5200 sats
10373                         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);
10374                 }
10375         } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
10376                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
10377                 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at update_fee-swallowed HTLC", ); }
10378                 {
10379                         let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10380                         *feerate_lock = *feerate_lock * 10;
10381                 }
10382                 nodes[0].node.timer_tick_occurred();
10383                 check_added_monitors!(nodes[0], 1);
10384                 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);
10385         }
10386
10387         let _ = nodes[0].node.get_and_clear_pending_msg_events();
10388         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
10389         added_monitors.clear();
10390 }
10391
10392 #[test]
10393 fn test_max_dust_htlc_exposure() {
10394         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
10395         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
10396         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
10397         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
10398         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
10399         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
10400         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
10401         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
10402         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
10403         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
10404         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
10405         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
10406 }
10407
10408 #[test]
10409 fn test_non_final_funding_tx() {
10410         let chanmon_cfgs = create_chanmon_cfgs(2);
10411         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10412         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10413         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10414
10415         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10416         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10417         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_message);
10418         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10419         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel_message);
10420
10421         let best_height = nodes[0].node.best_block.read().unwrap().height();
10422
10423         let chan_id = *nodes[0].network_chan_count.borrow();
10424         let events = nodes[0].node.get_and_clear_pending_events();
10425         let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
10426         assert_eq!(events.len(), 1);
10427         let mut tx = match events[0] {
10428                 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
10429                         // Timelock the transaction _beyond_ the best client height + 2.
10430                         Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 3), input: vec![input], output: vec![TxOut {
10431                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
10432                         }]}
10433                 },
10434                 _ => panic!("Unexpected event"),
10435         };
10436         // Transaction should fail as it's evaluated as non-final for propagation.
10437         match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
10438                 Err(APIError::APIMisuseError { err }) => {
10439                         assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
10440                 },
10441                 _ => panic!()
10442         }
10443
10444         // However, transaction should be accepted if it's in a +2 headroom from best block.
10445         tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
10446         assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
10447         get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
10448 }