3e79eecacbefd7aa3ea94d970c5e74062a691dc4
[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::Watch;
15 use chain::channelmonitor;
16 use chain::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
17 use chain::transaction::OutPoint;
18 use chain::keysinterface::{ChannelKeys, KeysInterface, SpendableOutputDescriptor};
19 use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
20 use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, RAACommitmentOrder, PaymentPreimage, PaymentHash, PaymentSecret, PaymentSendFailure, BREAKDOWN_TIMEOUT};
21 use ln::channel::{Channel, ChannelError};
22 use ln::{chan_utils, onion_utils};
23 use routing::router::{Route, RouteHop, get_route};
24 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
25 use ln::msgs;
26 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler,HTLCFailChannelUpdate, ErrorAction};
27 use util::enforcing_trait_impls::EnforcingChannelKeys;
28 use util::{byte_utils, test_utils};
29 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
30 use util::errors::APIError;
31 use util::ser::{Writeable, ReadableArgs, Readable};
32 use util::config::UserConfig;
33
34 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
35 use bitcoin::hashes::HashEngine;
36 use bitcoin::hash_types::{Txid, BlockHash, WPubkeyHash};
37 use bitcoin::util::bip143;
38 use bitcoin::util::address::Address;
39 use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
40 use bitcoin::blockdata::block::{Block, BlockHeader};
41 use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType, OutPoint as BitcoinOutPoint};
42 use bitcoin::blockdata::script::{Builder, Script};
43 use bitcoin::blockdata::opcodes;
44 use bitcoin::blockdata::constants::genesis_block;
45 use bitcoin::network::constants::Network;
46
47 use bitcoin::hashes::sha256::Hash as Sha256;
48 use bitcoin::hashes::Hash;
49
50 use bitcoin::secp256k1::{Secp256k1, Message};
51 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
52
53 use regex;
54
55 use std::collections::{BTreeSet, HashMap, HashSet};
56 use std::default::Default;
57 use std::sync::{Arc, Mutex};
58 use std::sync::atomic::Ordering;
59 use std::mem;
60
61 use ln::functional_test_utils::*;
62 use ln::chan_utils::PreCalculatedTxCreationKeys;
63
64 #[test]
65 fn test_insane_channel_opens() {
66         // Stand up a network of 2 nodes
67         let chanmon_cfgs = create_chanmon_cfgs(2);
68         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
69         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
70         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
71
72         // Instantiate channel parameters where we push the maximum msats given our
73         // funding satoshis
74         let channel_value_sat = 31337; // same as funding satoshis
75         let channel_reserve_satoshis = Channel::<EnforcingChannelKeys>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
76         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
77
78         // Have node0 initiate a channel to node1 with aforementioned parameters
79         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
80
81         // Extract the channel open message from node0 to node1
82         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
83
84         // Test helper that asserts we get the correct error string given a mutator
85         // that supposedly makes the channel open message insane
86         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
87                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
88                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
89                 assert_eq!(msg_events.len(), 1);
90                 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
91                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
92                         match action {
93                                 &ErrorAction::SendErrorMessage { .. } => {
94                                         nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
95                                 },
96                                 _ => panic!("unexpected event!"),
97                         }
98                 } else { assert!(false); }
99         };
100
101         use ln::channel::MAX_FUNDING_SATOSHIS;
102         use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
103
104         // Test all mutations that would make the channel open message insane
105         insane_open_helper(format!("Funding must be smaller than {}. It was {}", MAX_FUNDING_SATOSHIS, MAX_FUNDING_SATOSHIS).as_str(), |mut msg| { msg.funding_satoshis = MAX_FUNDING_SATOSHIS; msg });
106
107         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
108
109         insane_open_helper(r"push_msat \d+ was larger than funding value \d+", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
110
111         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
112
113         insane_open_helper(r"Bogus; channel reserve \(\d+\) is less than dust limit \(\d+\)", |mut msg| { msg.dust_limit_satoshis = msg.channel_reserve_satoshis + 1; msg });
114
115         insane_open_helper(r"Minimum htlc value \(\d+\) was larger than full channel value \(\d+\)", |mut msg| { msg.htlc_minimum_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000; msg });
116
117         insane_open_helper("They wanted our payments to be delayed by a needlessly long period", |mut msg| { msg.to_self_delay = MAX_LOCAL_BREAKDOWN_TIMEOUT + 1; msg });
118
119         insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
120
121         insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
122 }
123
124 #[test]
125 fn test_async_inbound_update_fee() {
126         let chanmon_cfgs = create_chanmon_cfgs(2);
127         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
128         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
129         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
130         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
131         let logger = test_utils::TestLogger::new();
132         let channel_id = chan.2;
133
134         // balancing
135         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
136
137         // A                                        B
138         // update_fee                            ->
139         // send (1) commitment_signed            -.
140         //                                       <- update_add_htlc/commitment_signed
141         // send (2) RAA (awaiting remote revoke) -.
142         // (1) commitment_signed is delivered    ->
143         //                                       .- send (3) RAA (awaiting remote revoke)
144         // (2) RAA is delivered                  ->
145         //                                       .- send (4) commitment_signed
146         //                                       <- (3) RAA is delivered
147         // send (5) commitment_signed            -.
148         //                                       <- (4) commitment_signed is delivered
149         // send (6) RAA                          -.
150         // (5) commitment_signed is delivered    ->
151         //                                       <- RAA
152         // (6) RAA is delivered                  ->
153
154         // First nodes[0] generates an update_fee
155         nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
156         check_added_monitors!(nodes[0], 1);
157
158         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
159         assert_eq!(events_0.len(), 1);
160         let (update_msg, commitment_signed) = match events_0[0] { // (1)
161                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
162                         (update_fee.as_ref(), commitment_signed)
163                 },
164                 _ => panic!("Unexpected event"),
165         };
166
167         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
168
169         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
170         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
171         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
172         nodes[1].node.send_payment(&get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV, &logger).unwrap(), our_payment_hash, &None).unwrap();
173         check_added_monitors!(nodes[1], 1);
174
175         let payment_event = {
176                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
177                 assert_eq!(events_1.len(), 1);
178                 SendEvent::from_event(events_1.remove(0))
179         };
180         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
181         assert_eq!(payment_event.msgs.len(), 1);
182
183         // ...now when the messages get delivered everyone should be happy
184         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
185         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
186         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
187         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
188         check_added_monitors!(nodes[0], 1);
189
190         // deliver(1), generate (3):
191         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
192         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
193         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
194         check_added_monitors!(nodes[1], 1);
195
196         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
197         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
198         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
199         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
200         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
201         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
202         assert!(bs_update.update_fee.is_none()); // (4)
203         check_added_monitors!(nodes[1], 1);
204
205         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
206         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
207         assert!(as_update.update_add_htlcs.is_empty()); // (5)
208         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
209         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
210         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
211         assert!(as_update.update_fee.is_none()); // (5)
212         check_added_monitors!(nodes[0], 1);
213
214         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
215         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
216         // only (6) so get_event_msg's assert(len == 1) passes
217         check_added_monitors!(nodes[0], 1);
218
219         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
220         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
221         check_added_monitors!(nodes[1], 1);
222
223         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
224         check_added_monitors!(nodes[0], 1);
225
226         let events_2 = nodes[0].node.get_and_clear_pending_events();
227         assert_eq!(events_2.len(), 1);
228         match events_2[0] {
229                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
230                 _ => panic!("Unexpected event"),
231         }
232
233         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
234         check_added_monitors!(nodes[1], 1);
235 }
236
237 #[test]
238 fn test_update_fee_unordered_raa() {
239         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
240         // crash in an earlier version of the update_fee patch)
241         let chanmon_cfgs = create_chanmon_cfgs(2);
242         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
243         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
244         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
245         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
246         let channel_id = chan.2;
247         let logger = test_utils::TestLogger::new();
248
249         // balancing
250         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
251
252         // First nodes[0] generates an update_fee
253         nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
254         check_added_monitors!(nodes[0], 1);
255
256         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
257         assert_eq!(events_0.len(), 1);
258         let update_msg = match events_0[0] { // (1)
259                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
260                         update_fee.as_ref()
261                 },
262                 _ => panic!("Unexpected event"),
263         };
264
265         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
266
267         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
268         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
269         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
270         nodes[1].node.send_payment(&get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV, &logger).unwrap(), our_payment_hash, &None).unwrap();
271         check_added_monitors!(nodes[1], 1);
272
273         let payment_event = {
274                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
275                 assert_eq!(events_1.len(), 1);
276                 SendEvent::from_event(events_1.remove(0))
277         };
278         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
279         assert_eq!(payment_event.msgs.len(), 1);
280
281         // ...now when the messages get delivered everyone should be happy
282         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
283         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
284         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
285         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
286         check_added_monitors!(nodes[0], 1);
287
288         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
289         check_added_monitors!(nodes[1], 1);
290
291         // We can't continue, sadly, because our (1) now has a bogus signature
292 }
293
294 #[test]
295 fn test_multi_flight_update_fee() {
296         let chanmon_cfgs = create_chanmon_cfgs(2);
297         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
298         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
299         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
300         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
301         let channel_id = chan.2;
302
303         // A                                        B
304         // update_fee/commitment_signed          ->
305         //                                       .- send (1) RAA and (2) commitment_signed
306         // update_fee (never committed)          ->
307         // (3) update_fee                        ->
308         // We have to manually generate the above update_fee, it is allowed by the protocol but we
309         // don't track which updates correspond to which revoke_and_ack responses so we're in
310         // AwaitingRAA mode and will not generate the update_fee yet.
311         //                                       <- (1) RAA delivered
312         // (3) is generated and send (4) CS      -.
313         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
314         // know the per_commitment_point to use for it.
315         //                                       <- (2) commitment_signed delivered
316         // revoke_and_ack                        ->
317         //                                          B should send no response here
318         // (4) commitment_signed delivered       ->
319         //                                       <- RAA/commitment_signed delivered
320         // revoke_and_ack                        ->
321
322         // First nodes[0] generates an update_fee
323         let initial_feerate = get_feerate!(nodes[0], channel_id);
324         nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
325         check_added_monitors!(nodes[0], 1);
326
327         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
328         assert_eq!(events_0.len(), 1);
329         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
330                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
331                         (update_fee.as_ref().unwrap(), commitment_signed)
332                 },
333                 _ => panic!("Unexpected event"),
334         };
335
336         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
337         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
338         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
339         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
340         check_added_monitors!(nodes[1], 1);
341
342         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
343         // transaction:
344         nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
345         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
346         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
347
348         // Create the (3) update_fee message that nodes[0] will generate before it does...
349         let mut update_msg_2 = msgs::UpdateFee {
350                 channel_id: update_msg_1.channel_id.clone(),
351                 feerate_per_kw: (initial_feerate + 30) as u32,
352         };
353
354         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
355
356         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
357         // Deliver (3)
358         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
359
360         // Deliver (1), generating (3) and (4)
361         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
362         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
363         check_added_monitors!(nodes[0], 1);
364         assert!(as_second_update.update_add_htlcs.is_empty());
365         assert!(as_second_update.update_fulfill_htlcs.is_empty());
366         assert!(as_second_update.update_fail_htlcs.is_empty());
367         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
368         // Check that the update_fee newly generated matches what we delivered:
369         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
370         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
371
372         // Deliver (2) commitment_signed
373         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
374         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
375         check_added_monitors!(nodes[0], 1);
376         // No commitment_signed so get_event_msg's assert(len == 1) passes
377
378         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
379         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
380         check_added_monitors!(nodes[1], 1);
381
382         // Delever (4)
383         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
384         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
385         check_added_monitors!(nodes[1], 1);
386
387         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
388         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
389         check_added_monitors!(nodes[0], 1);
390
391         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
392         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
393         // No commitment_signed so get_event_msg's assert(len == 1) passes
394         check_added_monitors!(nodes[0], 1);
395
396         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
397         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
398         check_added_monitors!(nodes[1], 1);
399 }
400
401 #[test]
402 fn test_1_conf_open() {
403         // Previously, if the minium_depth config was set to 1, we'd never send a funding_locked. This
404         // tests that we properly send one in that case.
405         let mut alice_config = UserConfig::default();
406         alice_config.own_channel_config.minimum_depth = 1;
407         alice_config.channel_options.announced_channel = true;
408         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
409         let mut bob_config = UserConfig::default();
410         bob_config.own_channel_config.minimum_depth = 1;
411         bob_config.channel_options.announced_channel = true;
412         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
413         let chanmon_cfgs = create_chanmon_cfgs(2);
414         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
415         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(alice_config), Some(bob_config)]);
416         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
417
418         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
419         let block = Block {
420                 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
421                 txdata: vec![tx],
422         };
423         connect_block(&nodes[1], &block, 1);
424         nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendFundingLocked, nodes[0].node.get_our_node_id()));
425
426         connect_block(&nodes[0], &block, 1);
427         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
428         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
429
430         for node in nodes {
431                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
432                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
433                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
434         }
435 }
436
437 fn do_test_sanity_on_in_flight_opens(steps: u8) {
438         // Previously, we had issues deserializing channels when we hadn't connected the first block
439         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
440         // serialization round-trips and simply do steps towards opening a channel and then drop the
441         // Node objects.
442
443         let chanmon_cfgs = create_chanmon_cfgs(2);
444         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
445         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
446         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
447
448         if steps & 0b1000_0000 != 0{
449                 let block = Block {
450                         header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
451                         txdata: vec![],
452                 };
453                 connect_block(&nodes[0], &block, 1);
454                 connect_block(&nodes[1], &block, 1);
455         }
456
457         if steps & 0x0f == 0 { return; }
458         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
459         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
460
461         if steps & 0x0f == 1 { return; }
462         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
463         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
464
465         if steps & 0x0f == 2 { return; }
466         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
467
468         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
469
470         if steps & 0x0f == 3 { return; }
471         nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
472         check_added_monitors!(nodes[0], 0);
473         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
474
475         if steps & 0x0f == 4 { return; }
476         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
477         {
478                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
479                 assert_eq!(added_monitors.len(), 1);
480                 assert_eq!(added_monitors[0].0, funding_output);
481                 added_monitors.clear();
482         }
483         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
484
485         if steps & 0x0f == 5 { return; }
486         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
487         {
488                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
489                 assert_eq!(added_monitors.len(), 1);
490                 assert_eq!(added_monitors[0].0, funding_output);
491                 added_monitors.clear();
492         }
493
494         let events_4 = nodes[0].node.get_and_clear_pending_events();
495         assert_eq!(events_4.len(), 1);
496         match events_4[0] {
497                 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
498                         assert_eq!(user_channel_id, 42);
499                         assert_eq!(*funding_txo, funding_output);
500                 },
501                 _ => panic!("Unexpected event"),
502         };
503
504         if steps & 0x0f == 6 { return; }
505         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx);
506
507         if steps & 0x0f == 7 { return; }
508         confirm_transaction(&nodes[0], &tx);
509         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
510 }
511
512 #[test]
513 fn test_sanity_on_in_flight_opens() {
514         do_test_sanity_on_in_flight_opens(0);
515         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
516         do_test_sanity_on_in_flight_opens(1);
517         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
518         do_test_sanity_on_in_flight_opens(2);
519         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
520         do_test_sanity_on_in_flight_opens(3);
521         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
522         do_test_sanity_on_in_flight_opens(4);
523         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
524         do_test_sanity_on_in_flight_opens(5);
525         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
526         do_test_sanity_on_in_flight_opens(6);
527         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
528         do_test_sanity_on_in_flight_opens(7);
529         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
530         do_test_sanity_on_in_flight_opens(8);
531         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
532 }
533
534 #[test]
535 fn test_update_fee_vanilla() {
536         let chanmon_cfgs = create_chanmon_cfgs(2);
537         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
538         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
539         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
540         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
541         let channel_id = chan.2;
542
543         let feerate = get_feerate!(nodes[0], channel_id);
544         nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
545         check_added_monitors!(nodes[0], 1);
546
547         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
548         assert_eq!(events_0.len(), 1);
549         let (update_msg, commitment_signed) = match events_0[0] {
550                         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 } } => {
551                         (update_fee.as_ref(), commitment_signed)
552                 },
553                 _ => panic!("Unexpected event"),
554         };
555         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
556
557         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
558         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
559         check_added_monitors!(nodes[1], 1);
560
561         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
562         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
563         check_added_monitors!(nodes[0], 1);
564
565         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
566         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
567         // No commitment_signed so get_event_msg's assert(len == 1) passes
568         check_added_monitors!(nodes[0], 1);
569
570         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
571         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
572         check_added_monitors!(nodes[1], 1);
573 }
574
575 #[test]
576 fn test_update_fee_that_funder_cannot_afford() {
577         let chanmon_cfgs = create_chanmon_cfgs(2);
578         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
579         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
580         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
581         let channel_value = 1888;
582         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000, InitFeatures::known(), InitFeatures::known());
583         let channel_id = chan.2;
584
585         let feerate = 260;
586         nodes[0].node.update_fee(channel_id, feerate).unwrap();
587         check_added_monitors!(nodes[0], 1);
588         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
589
590         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
591
592         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
593
594         //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
595         //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
596         {
597                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
598
599                 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
600                 let num_htlcs = commitment_tx.output.len() - 2;
601                 let total_fee: u64 = feerate as u64 * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
602                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
603                 actual_fee = channel_value - actual_fee;
604                 assert_eq!(total_fee, actual_fee);
605         }
606
607         //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
608         //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
609         nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
610         check_added_monitors!(nodes[0], 1);
611
612         let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
613
614         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap());
615
616         //While producing the commitment_signed response after handling a received update_fee request the
617         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
618         //Should produce and error.
619         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed);
620         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
621         check_added_monitors!(nodes[1], 1);
622         check_closed_broadcast!(nodes[1], true);
623 }
624
625 #[test]
626 fn test_update_fee_with_fundee_update_add_htlc() {
627         let chanmon_cfgs = create_chanmon_cfgs(2);
628         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
629         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
630         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
631         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
632         let channel_id = chan.2;
633         let logger = test_utils::TestLogger::new();
634
635         // balancing
636         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
637
638         let feerate = get_feerate!(nodes[0], channel_id);
639         nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
640         check_added_monitors!(nodes[0], 1);
641
642         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
643         assert_eq!(events_0.len(), 1);
644         let (update_msg, commitment_signed) = match events_0[0] {
645                         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 } } => {
646                         (update_fee.as_ref(), commitment_signed)
647                 },
648                 _ => panic!("Unexpected event"),
649         };
650         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
651         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
652         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
653         check_added_monitors!(nodes[1], 1);
654
655         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
656         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
657         let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, &Vec::new(), 800000, TEST_FINAL_CLTV, &logger).unwrap();
658
659         // nothing happens since node[1] is in AwaitingRemoteRevoke
660         nodes[1].node.send_payment(&route, our_payment_hash, &None).unwrap();
661         {
662                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
663                 assert_eq!(added_monitors.len(), 0);
664                 added_monitors.clear();
665         }
666         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
667         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
668         // node[1] has nothing to do
669
670         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
671         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
672         check_added_monitors!(nodes[0], 1);
673
674         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
675         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
676         // No commitment_signed so get_event_msg's assert(len == 1) passes
677         check_added_monitors!(nodes[0], 1);
678         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
679         check_added_monitors!(nodes[1], 1);
680         // AwaitingRemoteRevoke ends here
681
682         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
683         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
684         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
685         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
686         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
687         assert_eq!(commitment_update.update_fee.is_none(), true);
688
689         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
690         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
691         check_added_monitors!(nodes[0], 1);
692         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
693
694         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
695         check_added_monitors!(nodes[1], 1);
696         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
697
698         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
699         check_added_monitors!(nodes[1], 1);
700         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
701         // No commitment_signed so get_event_msg's assert(len == 1) passes
702
703         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
704         check_added_monitors!(nodes[0], 1);
705         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
706
707         expect_pending_htlcs_forwardable!(nodes[0]);
708
709         let events = nodes[0].node.get_and_clear_pending_events();
710         assert_eq!(events.len(), 1);
711         match events[0] {
712                 Event::PaymentReceived { .. } => { },
713                 _ => panic!("Unexpected event"),
714         };
715
716         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage, 800_000);
717
718         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000, 800_000);
719         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000, 800_000);
720         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
721 }
722
723 #[test]
724 fn test_update_fee() {
725         let chanmon_cfgs = create_chanmon_cfgs(2);
726         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
727         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
728         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
729         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
730         let channel_id = chan.2;
731
732         // A                                        B
733         // (1) update_fee/commitment_signed      ->
734         //                                       <- (2) revoke_and_ack
735         //                                       .- send (3) commitment_signed
736         // (4) update_fee/commitment_signed      ->
737         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
738         //                                       <- (3) commitment_signed delivered
739         // send (6) revoke_and_ack               -.
740         //                                       <- (5) deliver revoke_and_ack
741         // (6) deliver revoke_and_ack            ->
742         //                                       .- send (7) commitment_signed in response to (4)
743         //                                       <- (7) deliver commitment_signed
744         // revoke_and_ack                        ->
745
746         // Create and deliver (1)...
747         let feerate = get_feerate!(nodes[0], channel_id);
748         nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
749         check_added_monitors!(nodes[0], 1);
750
751         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
752         assert_eq!(events_0.len(), 1);
753         let (update_msg, commitment_signed) = match events_0[0] {
754                         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 } } => {
755                         (update_fee.as_ref(), commitment_signed)
756                 },
757                 _ => panic!("Unexpected event"),
758         };
759         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
760
761         // Generate (2) and (3):
762         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
763         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
764         check_added_monitors!(nodes[1], 1);
765
766         // Deliver (2):
767         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
768         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
769         check_added_monitors!(nodes[0], 1);
770
771         // Create and deliver (4)...
772         nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
773         check_added_monitors!(nodes[0], 1);
774         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
775         assert_eq!(events_0.len(), 1);
776         let (update_msg, commitment_signed) = match events_0[0] {
777                         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 } } => {
778                         (update_fee.as_ref(), commitment_signed)
779                 },
780                 _ => panic!("Unexpected event"),
781         };
782
783         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
784         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
785         check_added_monitors!(nodes[1], 1);
786         // ... creating (5)
787         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
788         // No commitment_signed so get_event_msg's assert(len == 1) passes
789
790         // Handle (3), creating (6):
791         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
792         check_added_monitors!(nodes[0], 1);
793         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
794         // No commitment_signed so get_event_msg's assert(len == 1) passes
795
796         // Deliver (5):
797         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
798         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
799         check_added_monitors!(nodes[0], 1);
800
801         // Deliver (6), creating (7):
802         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
803         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
804         assert!(commitment_update.update_add_htlcs.is_empty());
805         assert!(commitment_update.update_fulfill_htlcs.is_empty());
806         assert!(commitment_update.update_fail_htlcs.is_empty());
807         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
808         assert!(commitment_update.update_fee.is_none());
809         check_added_monitors!(nodes[1], 1);
810
811         // Deliver (7)
812         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
813         check_added_monitors!(nodes[0], 1);
814         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
815         // No commitment_signed so get_event_msg's assert(len == 1) passes
816
817         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
818         check_added_monitors!(nodes[1], 1);
819         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
820
821         assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
822         assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
823         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
824 }
825
826 #[test]
827 fn pre_funding_lock_shutdown_test() {
828         // Test sending a shutdown prior to funding_locked after funding generation
829         let chanmon_cfgs = create_chanmon_cfgs(2);
830         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
831         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
832         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
833         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0, InitFeatures::known(), InitFeatures::known());
834         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
835         connect_block(&nodes[0], &Block { header, txdata: vec![tx.clone()]}, 1);
836         connect_block(&nodes[1], &Block { header, txdata: vec![tx.clone()]}, 1);
837
838         nodes[0].node.close_channel(&OutPoint { txid: tx.txid(), index: 0 }.to_channel_id()).unwrap();
839         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
840         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
841         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
842         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
843
844         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
845         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
846         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
847         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
848         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
849         assert!(node_0_none.is_none());
850
851         assert!(nodes[0].node.list_channels().is_empty());
852         assert!(nodes[1].node.list_channels().is_empty());
853 }
854
855 #[test]
856 fn updates_shutdown_wait() {
857         // Test sending a shutdown with outstanding updates pending
858         let chanmon_cfgs = create_chanmon_cfgs(3);
859         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
860         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
861         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
862         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
863         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
864         let logger = test_utils::TestLogger::new();
865
866         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
867
868         nodes[0].node.close_channel(&chan_1.2).unwrap();
869         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
870         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
871         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
872         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
873
874         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
875         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
876
877         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
878
879         let net_graph_msg_handler0 = &nodes[0].net_graph_msg_handler;
880         let net_graph_msg_handler1 = &nodes[1].net_graph_msg_handler;
881         let route_1 = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler0.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
882         let route_2 = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler1.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
883         unwrap_send_err!(nodes[0].node.send_payment(&route_1, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
884         unwrap_send_err!(nodes[1].node.send_payment(&route_2, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
885
886         assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
887         check_added_monitors!(nodes[2], 1);
888         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
889         assert!(updates.update_add_htlcs.is_empty());
890         assert!(updates.update_fail_htlcs.is_empty());
891         assert!(updates.update_fail_malformed_htlcs.is_empty());
892         assert!(updates.update_fee.is_none());
893         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
894         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
895         check_added_monitors!(nodes[1], 1);
896         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
897         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
898
899         assert!(updates_2.update_add_htlcs.is_empty());
900         assert!(updates_2.update_fail_htlcs.is_empty());
901         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
902         assert!(updates_2.update_fee.is_none());
903         assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
904         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
905         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
906
907         let events = nodes[0].node.get_and_clear_pending_events();
908         assert_eq!(events.len(), 1);
909         match events[0] {
910                 Event::PaymentSent { ref payment_preimage } => {
911                         assert_eq!(our_payment_preimage, *payment_preimage);
912                 },
913                 _ => panic!("Unexpected event"),
914         }
915
916         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
917         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
918         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
919         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
920         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
921         assert!(node_0_none.is_none());
922
923         assert!(nodes[0].node.list_channels().is_empty());
924
925         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
926         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
927         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
928         assert!(nodes[1].node.list_channels().is_empty());
929         assert!(nodes[2].node.list_channels().is_empty());
930 }
931
932 #[test]
933 fn htlc_fail_async_shutdown() {
934         // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
935         let chanmon_cfgs = create_chanmon_cfgs(3);
936         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
937         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
938         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
939         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
940         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
941         let logger = test_utils::TestLogger::new();
942
943         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
944         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
945         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
946         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
947         check_added_monitors!(nodes[0], 1);
948         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
949         assert_eq!(updates.update_add_htlcs.len(), 1);
950         assert!(updates.update_fulfill_htlcs.is_empty());
951         assert!(updates.update_fail_htlcs.is_empty());
952         assert!(updates.update_fail_malformed_htlcs.is_empty());
953         assert!(updates.update_fee.is_none());
954
955         nodes[1].node.close_channel(&chan_1.2).unwrap();
956         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
957         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
958         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
959
960         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
961         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
962         check_added_monitors!(nodes[1], 1);
963         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
964         commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
965
966         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
967         assert!(updates_2.update_add_htlcs.is_empty());
968         assert!(updates_2.update_fulfill_htlcs.is_empty());
969         assert_eq!(updates_2.update_fail_htlcs.len(), 1);
970         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
971         assert!(updates_2.update_fee.is_none());
972
973         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]);
974         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
975
976         expect_payment_failed!(nodes[0], our_payment_hash, false);
977
978         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
979         assert_eq!(msg_events.len(), 2);
980         let node_0_closing_signed = match msg_events[0] {
981                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
982                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
983                         (*msg).clone()
984                 },
985                 _ => panic!("Unexpected event"),
986         };
987         match msg_events[1] {
988                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
989                         assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
990                 },
991                 _ => panic!("Unexpected event"),
992         }
993
994         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
995         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
996         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
997         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
998         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
999         assert!(node_0_none.is_none());
1000
1001         assert!(nodes[0].node.list_channels().is_empty());
1002
1003         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1004         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1005         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1006         assert!(nodes[1].node.list_channels().is_empty());
1007         assert!(nodes[2].node.list_channels().is_empty());
1008 }
1009
1010 fn do_test_shutdown_rebroadcast(recv_count: u8) {
1011         // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
1012         // messages delivered prior to disconnect
1013         let chanmon_cfgs = create_chanmon_cfgs(3);
1014         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1015         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1016         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1017         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1018         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1019
1020         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
1021
1022         nodes[1].node.close_channel(&chan_1.2).unwrap();
1023         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1024         if recv_count > 0 {
1025                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
1026                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1027                 if recv_count > 1 {
1028                         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
1029                 }
1030         }
1031
1032         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1033         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1034
1035         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1036         let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1037         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1038         let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1039
1040         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish);
1041         let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1042         assert!(node_1_shutdown == node_1_2nd_shutdown);
1043
1044         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish);
1045         let node_0_2nd_shutdown = if recv_count > 0 {
1046                 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1047                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
1048                 node_0_2nd_shutdown
1049         } else {
1050                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1051                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
1052                 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
1053         };
1054         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown);
1055
1056         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1057         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1058
1059         assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
1060         check_added_monitors!(nodes[2], 1);
1061         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1062         assert!(updates.update_add_htlcs.is_empty());
1063         assert!(updates.update_fail_htlcs.is_empty());
1064         assert!(updates.update_fail_malformed_htlcs.is_empty());
1065         assert!(updates.update_fee.is_none());
1066         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
1067         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
1068         check_added_monitors!(nodes[1], 1);
1069         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1070         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
1071
1072         assert!(updates_2.update_add_htlcs.is_empty());
1073         assert!(updates_2.update_fail_htlcs.is_empty());
1074         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
1075         assert!(updates_2.update_fee.is_none());
1076         assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
1077         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
1078         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
1079
1080         let events = nodes[0].node.get_and_clear_pending_events();
1081         assert_eq!(events.len(), 1);
1082         match events[0] {
1083                 Event::PaymentSent { ref payment_preimage } => {
1084                         assert_eq!(our_payment_preimage, *payment_preimage);
1085                 },
1086                 _ => panic!("Unexpected event"),
1087         }
1088
1089         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1090         if recv_count > 0 {
1091                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
1092                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1093                 assert!(node_1_closing_signed.is_some());
1094         }
1095
1096         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1097         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1098
1099         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1100         let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1101         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1102         if recv_count == 0 {
1103                 // If all closing_signeds weren't delivered we can just resume where we left off...
1104                 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1105
1106                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish);
1107                 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1108                 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
1109
1110                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1111                 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1112                 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
1113
1114                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown);
1115                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1116
1117                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown);
1118                 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1119                 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
1120
1121                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed);
1122                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1123                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
1124                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1125                 assert!(node_0_none.is_none());
1126         } else {
1127                 // If one node, however, received + responded with an identical closing_signed we end
1128                 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
1129                 // There isn't really anything better we can do simply, but in the future we might
1130                 // explore storing a set of recently-closed channels that got disconnected during
1131                 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
1132                 // give our counterparty enough time to (potentially) broadcast a cooperative closing
1133                 // transaction.
1134                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1135
1136                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1137                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1138                 assert_eq!(msg_events.len(), 1);
1139                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
1140                         match action {
1141                                 &ErrorAction::SendErrorMessage { ref msg } => {
1142                                         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
1143                                         assert_eq!(msg.channel_id, chan_1.2);
1144                                 },
1145                                 _ => panic!("Unexpected event!"),
1146                         }
1147                 } else { panic!("Needed SendErrorMessage close"); }
1148
1149                 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
1150                 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
1151                 // closing_signed so we do it ourselves
1152                 check_closed_broadcast!(nodes[0], false);
1153                 check_added_monitors!(nodes[0], 1);
1154         }
1155
1156         assert!(nodes[0].node.list_channels().is_empty());
1157
1158         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1159         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1160         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1161         assert!(nodes[1].node.list_channels().is_empty());
1162         assert!(nodes[2].node.list_channels().is_empty());
1163 }
1164
1165 #[test]
1166 fn test_shutdown_rebroadcast() {
1167         do_test_shutdown_rebroadcast(0);
1168         do_test_shutdown_rebroadcast(1);
1169         do_test_shutdown_rebroadcast(2);
1170 }
1171
1172 #[test]
1173 fn fake_network_test() {
1174         // Simple test which builds a network of ChannelManagers, connects them to each other, and
1175         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
1176         let chanmon_cfgs = create_chanmon_cfgs(4);
1177         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1178         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1179         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1180
1181         // Create some initial channels
1182         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1183         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1184         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1185
1186         // Rebalance the network a bit by relaying one payment through all the channels...
1187         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1188         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1189         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1190         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1191
1192         // Send some more payments
1193         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000, 1_000_000);
1194         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000, 1_000_000);
1195         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000, 1_000_000);
1196
1197         // Test failure packets
1198         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1199         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1200
1201         // Add a new channel that skips 3
1202         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1203
1204         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000, 1_000_000);
1205         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000, 1_000_000);
1206         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1207         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1208         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1209         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1210         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1211
1212         // Do some rebalance loop payments, simultaneously
1213         let mut hops = Vec::with_capacity(3);
1214         hops.push(RouteHop {
1215                 pubkey: nodes[2].node.get_our_node_id(),
1216                 node_features: NodeFeatures::empty(),
1217                 short_channel_id: chan_2.0.contents.short_channel_id,
1218                 channel_features: ChannelFeatures::empty(),
1219                 fee_msat: 0,
1220                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1221         });
1222         hops.push(RouteHop {
1223                 pubkey: nodes[3].node.get_our_node_id(),
1224                 node_features: NodeFeatures::empty(),
1225                 short_channel_id: chan_3.0.contents.short_channel_id,
1226                 channel_features: ChannelFeatures::empty(),
1227                 fee_msat: 0,
1228                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1229         });
1230         hops.push(RouteHop {
1231                 pubkey: nodes[1].node.get_our_node_id(),
1232                 node_features: NodeFeatures::empty(),
1233                 short_channel_id: chan_4.0.contents.short_channel_id,
1234                 channel_features: ChannelFeatures::empty(),
1235                 fee_msat: 1000000,
1236                 cltv_expiry_delta: TEST_FINAL_CLTV,
1237         });
1238         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;
1239         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;
1240         let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1241
1242         let mut hops = Vec::with_capacity(3);
1243         hops.push(RouteHop {
1244                 pubkey: nodes[3].node.get_our_node_id(),
1245                 node_features: NodeFeatures::empty(),
1246                 short_channel_id: chan_4.0.contents.short_channel_id,
1247                 channel_features: ChannelFeatures::empty(),
1248                 fee_msat: 0,
1249                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1250         });
1251         hops.push(RouteHop {
1252                 pubkey: nodes[2].node.get_our_node_id(),
1253                 node_features: NodeFeatures::empty(),
1254                 short_channel_id: chan_3.0.contents.short_channel_id,
1255                 channel_features: ChannelFeatures::empty(),
1256                 fee_msat: 0,
1257                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1258         });
1259         hops.push(RouteHop {
1260                 pubkey: nodes[1].node.get_our_node_id(),
1261                 node_features: NodeFeatures::empty(),
1262                 short_channel_id: chan_2.0.contents.short_channel_id,
1263                 channel_features: ChannelFeatures::empty(),
1264                 fee_msat: 1000000,
1265                 cltv_expiry_delta: TEST_FINAL_CLTV,
1266         });
1267         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;
1268         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;
1269         let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1270
1271         // Claim the rebalances...
1272         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1273         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1, 1_000_000);
1274
1275         // Add a duplicate new channel from 2 to 4
1276         let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1277
1278         // Send some payments across both channels
1279         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1280         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1281         let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1282
1283
1284         route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1285         let events = nodes[0].node.get_and_clear_pending_msg_events();
1286         assert_eq!(events.len(), 0);
1287         nodes[0].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), regex::Regex::new(r"Cannot send value that would put us over the max HTLC value in flight our peer will accept \(\d+\)").unwrap(), 1);
1288
1289         //TODO: Test that routes work again here as we've been notified that the channel is full
1290
1291         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3, 3_000_000);
1292         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4, 3_000_000);
1293         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5, 3_000_000);
1294
1295         // Close down the channels...
1296         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1297         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1298         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1299         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1300         close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1301 }
1302
1303 #[test]
1304 fn holding_cell_htlc_counting() {
1305         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1306         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1307         // commitment dance rounds.
1308         let chanmon_cfgs = create_chanmon_cfgs(3);
1309         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1310         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1311         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1312         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1313         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1314         let logger = test_utils::TestLogger::new();
1315
1316         let mut payments = Vec::new();
1317         for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1318                 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1319                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1320                 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1321                 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
1322                 payments.push((payment_preimage, payment_hash));
1323         }
1324         check_added_monitors!(nodes[1], 1);
1325
1326         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1327         assert_eq!(events.len(), 1);
1328         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1329         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1330
1331         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1332         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1333         // another HTLC.
1334         let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
1335         {
1336                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1337                 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1338                 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &None), true, APIError::ChannelUnavailable { ref err },
1339                         assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1340                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1341                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1342         }
1343
1344         // This should also be true if we try to forward a payment.
1345         let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
1346         {
1347                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1348                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1349                 nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
1350                 check_added_monitors!(nodes[0], 1);
1351         }
1352
1353         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1354         assert_eq!(events.len(), 1);
1355         let payment_event = SendEvent::from_event(events.pop().unwrap());
1356         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1357
1358         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1359         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1360         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1361         // fails), the second will process the resulting failure and fail the HTLC backward.
1362         expect_pending_htlcs_forwardable!(nodes[1]);
1363         expect_pending_htlcs_forwardable!(nodes[1]);
1364         check_added_monitors!(nodes[1], 1);
1365
1366         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1367         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1368         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1369
1370         let events = nodes[0].node.get_and_clear_pending_msg_events();
1371         assert_eq!(events.len(), 1);
1372         match events[0] {
1373                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
1374                         assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
1375                 },
1376                 _ => panic!("Unexpected event"),
1377         }
1378
1379         expect_payment_failed!(nodes[0], payment_hash_2, false);
1380
1381         // Now forward all the pending HTLCs and claim them back
1382         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1383         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1384         check_added_monitors!(nodes[2], 1);
1385
1386         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1387         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1388         check_added_monitors!(nodes[1], 1);
1389         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1390
1391         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1392         check_added_monitors!(nodes[1], 1);
1393         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1394
1395         for ref update in as_updates.update_add_htlcs.iter() {
1396                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1397         }
1398         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1399         check_added_monitors!(nodes[2], 1);
1400         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1401         check_added_monitors!(nodes[2], 1);
1402         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1403
1404         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1405         check_added_monitors!(nodes[1], 1);
1406         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1407         check_added_monitors!(nodes[1], 1);
1408         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1409
1410         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1411         check_added_monitors!(nodes[2], 1);
1412
1413         expect_pending_htlcs_forwardable!(nodes[2]);
1414
1415         let events = nodes[2].node.get_and_clear_pending_events();
1416         assert_eq!(events.len(), payments.len());
1417         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1418                 match event {
1419                         &Event::PaymentReceived { ref payment_hash, .. } => {
1420                                 assert_eq!(*payment_hash, *hash);
1421                         },
1422                         _ => panic!("Unexpected event"),
1423                 };
1424         }
1425
1426         for (preimage, _) in payments.drain(..) {
1427                 claim_payment(&nodes[1], &[&nodes[2]], preimage, 100_000);
1428         }
1429
1430         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000, 1_000_000);
1431 }
1432
1433 #[test]
1434 fn duplicate_htlc_test() {
1435         // Test that we accept duplicate payment_hash HTLCs across the network and that
1436         // claiming/failing them are all separate and don't affect each other
1437         let chanmon_cfgs = create_chanmon_cfgs(6);
1438         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1439         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1440         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1441
1442         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1443         create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1444         create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1445         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1446         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1447         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1448
1449         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1450
1451         *nodes[0].network_payment_count.borrow_mut() -= 1;
1452         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1453
1454         *nodes[0].network_payment_count.borrow_mut() -= 1;
1455         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1456
1457         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage, 1_000_000);
1458         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1459         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage, 1_000_000);
1460 }
1461
1462 #[test]
1463 fn test_duplicate_htlc_different_direction_onchain() {
1464         // Test that ChannelMonitor doesn't generate 2 preimage txn
1465         // when we have 2 HTLCs with same preimage that go across a node
1466         // in opposite directions.
1467         let chanmon_cfgs = create_chanmon_cfgs(2);
1468         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1469         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1470         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1471
1472         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1473         let logger = test_utils::TestLogger::new();
1474
1475         // balancing
1476         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
1477
1478         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1479
1480         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1481         let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, &Vec::new(), 800_000, TEST_FINAL_CLTV, &logger).unwrap();
1482         send_along_route_with_hash(&nodes[1], route, &vec!(&nodes[0])[..], 800_000, payment_hash);
1483
1484         // Provide preimage to node 0 by claiming payment
1485         nodes[0].node.claim_funds(payment_preimage, &None, 800_000);
1486         check_added_monitors!(nodes[0], 1);
1487
1488         // Broadcast node 1 commitment txn
1489         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1490
1491         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1492         let mut has_both_htlcs = 0; // check htlcs match ones committed
1493         for outp in remote_txn[0].output.iter() {
1494                 if outp.value == 800_000 / 1000 {
1495                         has_both_htlcs += 1;
1496                 } else if outp.value == 900_000 / 1000 {
1497                         has_both_htlcs += 1;
1498                 }
1499         }
1500         assert_eq!(has_both_htlcs, 2);
1501
1502         let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1503         connect_block(&nodes[0], &Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
1504         check_added_monitors!(nodes[0], 1);
1505
1506         // Check we only broadcast 1 timeout tx
1507         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1508         let htlc_pair = if claim_txn[0].output[0].value == 800_000 / 1000 { (claim_txn[0].clone(), claim_txn[1].clone()) } else { (claim_txn[1].clone(), claim_txn[0].clone()) };
1509         assert_eq!(claim_txn.len(), 5);
1510         check_spends!(claim_txn[2], chan_1.3);
1511         check_spends!(claim_txn[3], claim_txn[2]);
1512         assert_eq!(htlc_pair.0.input.len(), 1);
1513         assert_eq!(htlc_pair.0.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1514         check_spends!(htlc_pair.0, remote_txn[0]);
1515         assert_eq!(htlc_pair.1.input.len(), 1);
1516         assert_eq!(htlc_pair.1.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1517         check_spends!(htlc_pair.1, remote_txn[0]);
1518
1519         let events = nodes[0].node.get_and_clear_pending_msg_events();
1520         assert_eq!(events.len(), 2);
1521         for e in events {
1522                 match e {
1523                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1524                         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, .. } } => {
1525                                 assert!(update_add_htlcs.is_empty());
1526                                 assert!(update_fail_htlcs.is_empty());
1527                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1528                                 assert!(update_fail_malformed_htlcs.is_empty());
1529                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1530                         },
1531                         _ => panic!("Unexpected event"),
1532                 }
1533         }
1534 }
1535
1536 #[test]
1537 fn test_basic_channel_reserve() {
1538         let chanmon_cfgs = create_chanmon_cfgs(2);
1539         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1540         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1541         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1542         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1543         let logger = test_utils::TestLogger::new();
1544
1545         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1546         let channel_reserve = chan_stat.channel_reserve_msat;
1547
1548         // The 2* and +1 are for the fee spike reserve.
1549         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
1550         let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1);
1551         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1552         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1553         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), max_can_send + 1, TEST_FINAL_CLTV, &logger).unwrap();
1554         let err = nodes[0].node.send_payment(&route, our_payment_hash, &None).err().unwrap();
1555         match err {
1556                 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1557                         match &fails[0] {
1558                                 &APIError::ChannelUnavailable{ref err} =>
1559                                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1560                                 _ => panic!("Unexpected error variant"),
1561                         }
1562                 },
1563                 _ => panic!("Unexpected error variant"),
1564         }
1565         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1566         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);
1567
1568         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send, max_can_send);
1569 }
1570
1571 #[test]
1572 fn test_fee_spike_violation_fails_htlc() {
1573         let chanmon_cfgs = create_chanmon_cfgs(2);
1574         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1575         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1576         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1577         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1578         let logger = test_utils::TestLogger::new();
1579
1580         macro_rules! get_route_and_payment_hash {
1581                 ($recv_value: expr) => {{
1582                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1583                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler.network_graph.read().unwrap();
1584                         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1585                         (route, payment_hash, payment_preimage)
1586                 }}
1587         };
1588
1589         let (route, payment_hash, _) = get_route_and_payment_hash!(3460001);
1590         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1591         let secp_ctx = Secp256k1::new();
1592         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1593
1594         let cur_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1595
1596         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1597         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &None, cur_height).unwrap();
1598         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1599         let msg = msgs::UpdateAddHTLC {
1600                 channel_id: chan.2,
1601                 htlc_id: 0,
1602                 amount_msat: htlc_msat,
1603                 payment_hash: payment_hash,
1604                 cltv_expiry: htlc_cltv,
1605                 onion_routing_packet: onion_packet,
1606         };
1607
1608         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1609
1610         // Now manually create the commitment_signed message corresponding to the update_add
1611         // nodes[0] just sent. In the code for construction of this message, "local" refers
1612         // to the sender of the message, and "remote" refers to the receiver.
1613
1614         let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1615
1616         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1617
1618         // Get the EnforcingChannelKeys for each channel, which will be used to (1) get the keys
1619         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1620         let (local_revocation_basepoint, local_htlc_basepoint, local_payment_point, local_secret, local_secret2) = {
1621                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1622                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1623                 let chan_keys = local_chan.get_keys();
1624                 let pubkeys = chan_keys.pubkeys();
1625                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint, pubkeys.payment_point,
1626                  chan_keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER), chan_keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2))
1627         };
1628         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_payment_point, remote_secret1) = {
1629                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1630                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1631                 let chan_keys = remote_chan.get_keys();
1632                 let pubkeys = chan_keys.pubkeys();
1633                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint, pubkeys.payment_point,
1634                  chan_keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1))
1635         };
1636
1637         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1638         let commitment_secret = SecretKey::from_slice(&remote_secret1).unwrap();
1639         let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &commitment_secret);
1640         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &per_commitment_point, &remote_delayed_payment_basepoint,
1641                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1642
1643         // Build the remote commitment transaction so we can sign it, and then later use the
1644         // signature for the commitment_signed message.
1645         let local_chan_balance = 1313;
1646         let static_payment_pk = local_payment_point.serialize();
1647         let remote_commit_tx_output = TxOut {
1648                                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0)
1649                                                              .push_slice(&WPubkeyHash::hash(&static_payment_pk)[..])
1650                                                              .into_script(),
1651                 value: local_chan_balance as u64
1652         };
1653
1654         let local_commit_tx_output = TxOut {
1655                 script_pubkey: chan_utils::get_revokeable_redeemscript(&commit_tx_keys.revocation_key,
1656                                                                                BREAKDOWN_TIMEOUT,
1657                                                                                &commit_tx_keys.broadcaster_delayed_payment_key).to_v0_p2wsh(),
1658                                 value: 95000,
1659         };
1660
1661         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1662                 offered: false,
1663                 amount_msat: 3460001,
1664                 cltv_expiry: htlc_cltv,
1665                 payment_hash: payment_hash,
1666                 transaction_output_index: Some(1),
1667         };
1668
1669         let htlc_output = TxOut {
1670                 script_pubkey: chan_utils::get_htlc_redeemscript(&accepted_htlc_info, &commit_tx_keys).to_v0_p2wsh(),
1671                 value: 3460001 / 1000
1672         };
1673
1674         let commit_tx_obscure_factor = {
1675                 let mut sha = Sha256::engine();
1676                 let remote_payment_point = &remote_payment_point.serialize();
1677                 sha.input(&local_payment_point.serialize());
1678                 sha.input(remote_payment_point);
1679                 let res = Sha256::from_engine(sha).into_inner();
1680
1681                 ((res[26] as u64) << 5*8) |
1682                 ((res[27] as u64) << 4*8) |
1683                 ((res[28] as u64) << 3*8) |
1684                 ((res[29] as u64) << 2*8) |
1685                 ((res[30] as u64) << 1*8) |
1686                 ((res[31] as u64) << 0*8)
1687         };
1688         let commitment_number = 1;
1689         let obscured_commitment_transaction_number = commit_tx_obscure_factor ^ commitment_number;
1690         let lock_time = ((0x20 as u32) << 8*3) | ((obscured_commitment_transaction_number & 0xffffffu64) as u32);
1691         let input = TxIn {
1692                 previous_output: BitcoinOutPoint { txid: chan.3.txid(), vout: 0 },
1693                 script_sig: Script::new(),
1694                 sequence: ((0x80 as u32) << 8*3) | ((obscured_commitment_transaction_number >> 3*8) as u32),
1695                 witness: Vec::new(),
1696         };
1697
1698         let commit_tx = Transaction {
1699                 version: 2,
1700                 lock_time,
1701                 input: vec![input],
1702                 output: vec![remote_commit_tx_output, htlc_output, local_commit_tx_output],
1703         };
1704         let res = {
1705                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1706                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1707                 let local_chan_keys = local_chan.get_keys();
1708                 let pre_commit_tx_keys = PreCalculatedTxCreationKeys::new(commit_tx_keys);
1709                 local_chan_keys.sign_counterparty_commitment(feerate_per_kw, &commit_tx, &pre_commit_tx_keys, &[&accepted_htlc_info], &secp_ctx).unwrap()
1710         };
1711
1712         let commit_signed_msg = msgs::CommitmentSigned {
1713                 channel_id: chan.2,
1714                 signature: res.0,
1715                 htlc_signatures: res.1
1716         };
1717
1718         // Send the commitment_signed message to the nodes[1].
1719         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1720         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1721
1722         // Send the RAA to nodes[1].
1723         let per_commitment_secret = local_secret;
1724         let next_secret = SecretKey::from_slice(&local_secret2).unwrap();
1725         let next_per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &next_secret);
1726         let raa_msg = msgs::RevokeAndACK{ channel_id: chan.2, per_commitment_secret, next_per_commitment_point};
1727         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1728
1729         let events = nodes[1].node.get_and_clear_pending_msg_events();
1730         assert_eq!(events.len(), 1);
1731         // Make sure the HTLC failed in the way we expect.
1732         match events[0] {
1733                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1734                         assert_eq!(update_fail_htlcs.len(), 1);
1735                         update_fail_htlcs[0].clone()
1736                 },
1737                 _ => panic!("Unexpected event"),
1738         };
1739         nodes[1].logger.assert_log("lightning::ln::channel".to_string(), "Attempting to fail HTLC due to fee spike buffer violation".to_string(), 1);
1740
1741         check_added_monitors!(nodes[1], 2);
1742 }
1743
1744 #[test]
1745 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1746         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1747         // Set the fee rate for the channel very high, to the point where the fundee
1748         // sending any amount would result in a channel reserve violation. In this test
1749         // we check that we would be prevented from sending an HTLC in this situation.
1750         chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1751         chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1752         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1753         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1754         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1755         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1756         let logger = test_utils::TestLogger::new();
1757
1758         macro_rules! get_route_and_payment_hash {
1759                 ($recv_value: expr) => {{
1760                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1761                         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1762                         let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes.first().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1763                         (route, payment_hash, payment_preimage)
1764                 }}
1765         };
1766
1767         let (route, our_payment_hash, _) = get_route_and_payment_hash!(1000);
1768         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1769                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1770         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1771         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);
1772 }
1773
1774 #[test]
1775 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1776         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1777         // Set the fee rate for the channel very high, to the point where the funder
1778         // receiving 1 update_add_htlc would result in them closing the channel due
1779         // to channel reserve violation. This close could also happen if the fee went
1780         // up a more realistic amount, but many HTLCs were outstanding at the time of
1781         // the update_add_htlc.
1782         chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1783         chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1784         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1785         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1786         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1787         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1788         let logger = test_utils::TestLogger::new();
1789
1790         macro_rules! get_route_and_payment_hash {
1791                 ($recv_value: expr) => {{
1792                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1793                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1794                         let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes.first().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1795                         (route, payment_hash, payment_preimage)
1796                 }}
1797         };
1798
1799         let (route, payment_hash, _) = get_route_and_payment_hash!(1000);
1800         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1801         let secp_ctx = Secp256k1::new();
1802         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1803         let cur_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1804         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1805         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 1000, &None, cur_height).unwrap();
1806         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1807         let msg = msgs::UpdateAddHTLC {
1808                 channel_id: chan.2,
1809                 htlc_id: 1,
1810                 amount_msat: htlc_msat + 1,
1811                 payment_hash: payment_hash,
1812                 cltv_expiry: htlc_cltv,
1813                 onion_routing_packet: onion_packet,
1814         };
1815
1816         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1817         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1818         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);
1819         assert_eq!(nodes[0].node.list_channels().len(), 0);
1820         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1821         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1822         check_added_monitors!(nodes[0], 1);
1823 }
1824
1825 #[test]
1826 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1827         let chanmon_cfgs = create_chanmon_cfgs(3);
1828         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1829         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1830         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1831         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1832         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1833         let logger = test_utils::TestLogger::new();
1834
1835         macro_rules! get_route_and_payment_hash {
1836                 ($recv_value: expr) => {{
1837                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1838                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1839                         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1840                         (route, payment_hash, payment_preimage)
1841                 }}
1842         };
1843
1844         let feemsat = 239;
1845         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1846         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1847         let feerate = get_feerate!(nodes[0], chan.2);
1848
1849         // Add a 2* and +1 for the fee spike reserve.
1850         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1);
1851         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;
1852         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1853
1854         // Add a pending HTLC.
1855         let (route_1, our_payment_hash_1, _) = get_route_and_payment_hash!(amt_msat_1);
1856         let payment_event_1 = {
1857                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
1858                 check_added_monitors!(nodes[0], 1);
1859
1860                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1861                 assert_eq!(events.len(), 1);
1862                 SendEvent::from_event(events.remove(0))
1863         };
1864         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1865
1866         // Attempt to trigger a channel reserve violation --> payment failure.
1867         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2);
1868         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;
1869         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1870         let (route_2, _, _) = get_route_and_payment_hash!(amt_msat_2);
1871
1872         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1873         let secp_ctx = Secp256k1::new();
1874         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1875         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1876         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1877         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height).unwrap();
1878         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1879         let msg = msgs::UpdateAddHTLC {
1880                 channel_id: chan.2,
1881                 htlc_id: 1,
1882                 amount_msat: htlc_msat + 1,
1883                 payment_hash: our_payment_hash_1,
1884                 cltv_expiry: htlc_cltv,
1885                 onion_routing_packet: onion_packet,
1886         };
1887
1888         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1889         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1890         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1891         assert_eq!(nodes[1].node.list_channels().len(), 1);
1892         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1893         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1894         check_added_monitors!(nodes[1], 1);
1895 }
1896
1897 #[test]
1898 fn test_inbound_outbound_capacity_is_not_zero() {
1899         let chanmon_cfgs = create_chanmon_cfgs(2);
1900         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1901         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1902         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1903         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1904         let channels0 = node_chanmgrs[0].list_channels();
1905         let channels1 = node_chanmgrs[1].list_channels();
1906         assert_eq!(channels0.len(), 1);
1907         assert_eq!(channels1.len(), 1);
1908
1909         assert_eq!(channels0[0].inbound_capacity_msat, 95000000);
1910         assert_eq!(channels1[0].outbound_capacity_msat, 95000000);
1911
1912         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000);
1913         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000);
1914 }
1915
1916 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64) -> u64 {
1917         (COMMITMENT_TX_BASE_WEIGHT + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1918 }
1919
1920 #[test]
1921 fn test_channel_reserve_holding_cell_htlcs() {
1922         let chanmon_cfgs = create_chanmon_cfgs(3);
1923         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1924         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1925         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1926         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1927         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1928         let logger = test_utils::TestLogger::new();
1929
1930         let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1931         let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1932
1933         let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1934         let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1935
1936         macro_rules! get_route_and_payment_hash {
1937                 ($recv_value: expr) => {{
1938                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1939                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1940                         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1941                         (route, payment_hash, payment_preimage)
1942                 }}
1943         };
1944
1945         macro_rules! expect_forward {
1946                 ($node: expr) => {{
1947                         let mut events = $node.node.get_and_clear_pending_msg_events();
1948                         assert_eq!(events.len(), 1);
1949                         check_added_monitors!($node, 1);
1950                         let payment_event = SendEvent::from_event(events.remove(0));
1951                         payment_event
1952                 }}
1953         }
1954
1955         let feemsat = 239; // somehow we know?
1956         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1957         let feerate = get_feerate!(nodes[0], chan_1.2);
1958
1959         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1960
1961         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1962         {
1963                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
1964                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1965                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1966                         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)));
1967                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1968                 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);
1969         }
1970
1971         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1972         // nodes[0]'s wealth
1973         loop {
1974                 let amt_msat = recv_value_0 + total_fee_msat;
1975                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1976                 // Also, ensure that each payment has enough to be over the dust limit to
1977                 // ensure it'll be included in each commit tx fee calculation.
1978                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1979                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1980                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1981                         break;
1982                 }
1983                 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0, recv_value_0);
1984
1985                 let (stat01_, stat11_, stat12_, stat22_) = (
1986                         get_channel_value_stat!(nodes[0], chan_1.2),
1987                         get_channel_value_stat!(nodes[1], chan_1.2),
1988                         get_channel_value_stat!(nodes[1], chan_2.2),
1989                         get_channel_value_stat!(nodes[2], chan_2.2),
1990                 );
1991
1992                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1993                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1994                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1995                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1996                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1997         }
1998
1999         // adding pending output.
2000         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
2001         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
2002         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
2003         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
2004         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
2005         // cases where 1 msat over X amount will cause a payment failure, but anything less than
2006         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
2007         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
2008         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
2009         // policy.
2010         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1);
2011         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
2012         let amt_msat_1 = recv_value_1 + total_fee_msat;
2013
2014         let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
2015         let payment_event_1 = {
2016                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
2017                 check_added_monitors!(nodes[0], 1);
2018
2019                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2020                 assert_eq!(events.len(), 1);
2021                 SendEvent::from_event(events.remove(0))
2022         };
2023         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
2024
2025         // channel reserve test with htlc pending output > 0
2026         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
2027         {
2028                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
2029                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
2030                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
2031                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2032         }
2033
2034         // split the rest to test holding cell
2035         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
2036         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
2037         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
2038         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
2039         {
2040                 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
2041                 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);
2042         }
2043
2044         // now see if they go through on both sides
2045         let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
2046         // but this will stuck in the holding cell
2047         nodes[0].node.send_payment(&route_21, our_payment_hash_21, &None).unwrap();
2048         check_added_monitors!(nodes[0], 0);
2049         let events = nodes[0].node.get_and_clear_pending_events();
2050         assert_eq!(events.len(), 0);
2051
2052         // test with outbound holding cell amount > 0
2053         {
2054                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
2055                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
2056                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
2057                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2058                 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);
2059         }
2060
2061         let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
2062         // this will also stuck in the holding cell
2063         nodes[0].node.send_payment(&route_22, our_payment_hash_22, &None).unwrap();
2064         check_added_monitors!(nodes[0], 0);
2065         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
2066         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2067
2068         // flush the pending htlc
2069         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
2070         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2071         check_added_monitors!(nodes[1], 1);
2072
2073         // the pending htlc should be promoted to committed
2074         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
2075         check_added_monitors!(nodes[0], 1);
2076         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2077
2078         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
2079         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2080         // No commitment_signed so get_event_msg's assert(len == 1) passes
2081         check_added_monitors!(nodes[0], 1);
2082
2083         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
2084         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2085         check_added_monitors!(nodes[1], 1);
2086
2087         expect_pending_htlcs_forwardable!(nodes[1]);
2088
2089         let ref payment_event_11 = expect_forward!(nodes[1]);
2090         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
2091         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
2092
2093         expect_pending_htlcs_forwardable!(nodes[2]);
2094         expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
2095
2096         // flush the htlcs in the holding cell
2097         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
2098         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
2099         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
2100         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
2101         expect_pending_htlcs_forwardable!(nodes[1]);
2102
2103         let ref payment_event_3 = expect_forward!(nodes[1]);
2104         assert_eq!(payment_event_3.msgs.len(), 2);
2105         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
2106         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
2107
2108         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2109         expect_pending_htlcs_forwardable!(nodes[2]);
2110
2111         let events = nodes[2].node.get_and_clear_pending_events();
2112         assert_eq!(events.len(), 2);
2113         match events[0] {
2114                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2115                         assert_eq!(our_payment_hash_21, *payment_hash);
2116                         assert_eq!(*payment_secret, None);
2117                         assert_eq!(recv_value_21, amt);
2118                 },
2119                 _ => panic!("Unexpected event"),
2120         }
2121         match events[1] {
2122                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2123                         assert_eq!(our_payment_hash_22, *payment_hash);
2124                         assert_eq!(None, *payment_secret);
2125                         assert_eq!(recv_value_22, amt);
2126                 },
2127                 _ => panic!("Unexpected event"),
2128         }
2129
2130         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1, recv_value_1);
2131         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21, recv_value_21);
2132         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22, recv_value_22);
2133
2134         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1);
2135         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2136         {
2137                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_3 + 1);
2138                 let err = nodes[0].node.send_payment(&route, our_payment_hash, &None).err().unwrap();
2139                 match err {
2140                         PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
2141                                 match &fails[0] {
2142                                         &APIError::ChannelUnavailable{ref err} =>
2143                                                 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
2144                                         _ => panic!("Unexpected error variant"),
2145                                 }
2146                         },
2147                         _ => panic!("Unexpected error variant"),
2148                 }
2149                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2150                 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(), 3);
2151         }
2152
2153         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3, recv_value_3);
2154
2155         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1);
2156         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);
2157         let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2158         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2159         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2160
2161         let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2162         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2163 }
2164
2165 #[test]
2166 fn channel_reserve_in_flight_removes() {
2167         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2168         // can send to its counterparty, but due to update ordering, the other side may not yet have
2169         // considered those HTLCs fully removed.
2170         // This tests that we don't count HTLCs which will not be included in the next remote
2171         // commitment transaction towards the reserve value (as it implies no commitment transaction
2172         // will be generated which violates the remote reserve value).
2173         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2174         // To test this we:
2175         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2176         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2177         //    you only consider the value of the first HTLC, it may not),
2178         //  * start routing a third HTLC from A to B,
2179         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2180         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2181         //  * deliver the first fulfill from B
2182         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2183         //    claim,
2184         //  * deliver A's response CS and RAA.
2185         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2186         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2187         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2188         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2189         let chanmon_cfgs = create_chanmon_cfgs(2);
2190         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2191         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2192         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2193         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2194         let logger = test_utils::TestLogger::new();
2195
2196         let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2197         // Route the first two HTLCs.
2198         let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
2199         let (payment_preimage_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
2200
2201         // Start routing the third HTLC (this is just used to get everyone in the right state).
2202         let (payment_preimage_3, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
2203         let send_1 = {
2204                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
2205                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
2206                 nodes[0].node.send_payment(&route, payment_hash_3, &None).unwrap();
2207                 check_added_monitors!(nodes[0], 1);
2208                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2209                 assert_eq!(events.len(), 1);
2210                 SendEvent::from_event(events.remove(0))
2211         };
2212
2213         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2214         // initial fulfill/CS.
2215         assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000));
2216         check_added_monitors!(nodes[1], 1);
2217         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2218
2219         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2220         // remove the second HTLC when we send the HTLC back from B to A.
2221         assert!(nodes[1].node.claim_funds(payment_preimage_2, &None, 20000));
2222         check_added_monitors!(nodes[1], 1);
2223         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2224
2225         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2226         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2227         check_added_monitors!(nodes[0], 1);
2228         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2229         expect_payment_sent!(nodes[0], payment_preimage_1);
2230
2231         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2232         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2233         check_added_monitors!(nodes[1], 1);
2234         // B is already AwaitingRAA, so cant generate a CS here
2235         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2236
2237         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2238         check_added_monitors!(nodes[1], 1);
2239         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2240
2241         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2242         check_added_monitors!(nodes[0], 1);
2243         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2244
2245         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2246         check_added_monitors!(nodes[1], 1);
2247         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2248
2249         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2250         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2251         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2252         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2253         // on-chain as necessary).
2254         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2255         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2256         check_added_monitors!(nodes[0], 1);
2257         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2258         expect_payment_sent!(nodes[0], payment_preimage_2);
2259
2260         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2261         check_added_monitors!(nodes[1], 1);
2262         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2263
2264         expect_pending_htlcs_forwardable!(nodes[1]);
2265         expect_payment_received!(nodes[1], payment_hash_3, 100000);
2266
2267         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2268         // resolve the second HTLC from A's point of view.
2269         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2270         check_added_monitors!(nodes[0], 1);
2271         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2272
2273         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2274         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2275         let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[1]);
2276         let send_2 = {
2277                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
2278                 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, &[], 10000, TEST_FINAL_CLTV, &logger).unwrap();
2279                 nodes[1].node.send_payment(&route, payment_hash_4, &None).unwrap();
2280                 check_added_monitors!(nodes[1], 1);
2281                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2282                 assert_eq!(events.len(), 1);
2283                 SendEvent::from_event(events.remove(0))
2284         };
2285
2286         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2287         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2288         check_added_monitors!(nodes[0], 1);
2289         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2290
2291         // Now just resolve all the outstanding messages/HTLCs for completeness...
2292
2293         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2294         check_added_monitors!(nodes[1], 1);
2295         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2296
2297         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2298         check_added_monitors!(nodes[1], 1);
2299
2300         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2301         check_added_monitors!(nodes[0], 1);
2302         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2303
2304         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2305         check_added_monitors!(nodes[1], 1);
2306         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2307
2308         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2309         check_added_monitors!(nodes[0], 1);
2310
2311         expect_pending_htlcs_forwardable!(nodes[0]);
2312         expect_payment_received!(nodes[0], payment_hash_4, 10000);
2313
2314         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4, 10_000);
2315         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3, 100_000);
2316 }
2317
2318 #[test]
2319 fn channel_monitor_network_test() {
2320         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2321         // tests that ChannelMonitor is able to recover from various states.
2322         let chanmon_cfgs = create_chanmon_cfgs(5);
2323         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2324         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2325         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2326
2327         // Create some initial channels
2328         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2329         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2330         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2331         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2332
2333         // Rebalance the network a bit by relaying one payment through all the channels...
2334         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2335         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2336         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2337         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2338
2339         // Simple case with no pending HTLCs:
2340         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2341         check_added_monitors!(nodes[1], 1);
2342         {
2343                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2344                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2345                 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
2346                 check_added_monitors!(nodes[0], 1);
2347                 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2348         }
2349         get_announce_close_broadcast_events(&nodes, 0, 1);
2350         assert_eq!(nodes[0].node.list_channels().len(), 0);
2351         assert_eq!(nodes[1].node.list_channels().len(), 1);
2352
2353         // One pending HTLC is discarded by the force-close:
2354         let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2355
2356         // Simple case of one pending HTLC to HTLC-Timeout
2357         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2358         check_added_monitors!(nodes[1], 1);
2359         {
2360                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2361                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2362                 connect_block(&nodes[2], &Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
2363                 check_added_monitors!(nodes[2], 1);
2364                 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2365         }
2366         get_announce_close_broadcast_events(&nodes, 1, 2);
2367         assert_eq!(nodes[1].node.list_channels().len(), 0);
2368         assert_eq!(nodes[2].node.list_channels().len(), 1);
2369
2370         macro_rules! claim_funds {
2371                 ($node: expr, $prev_node: expr, $preimage: expr, $amount: expr) => {
2372                         {
2373                                 assert!($node.node.claim_funds($preimage, &None, $amount));
2374                                 check_added_monitors!($node, 1);
2375
2376                                 let events = $node.node.get_and_clear_pending_msg_events();
2377                                 assert_eq!(events.len(), 1);
2378                                 match events[0] {
2379                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2380                                                 assert!(update_add_htlcs.is_empty());
2381                                                 assert!(update_fail_htlcs.is_empty());
2382                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2383                                         },
2384                                         _ => panic!("Unexpected event"),
2385                                 };
2386                         }
2387                 }
2388         }
2389
2390         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2391         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2392         nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2393         check_added_monitors!(nodes[2], 1);
2394         let node2_commitment_txid;
2395         {
2396                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2397                 node2_commitment_txid = node_txn[0].txid();
2398
2399                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2400                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, 3_000_000);
2401
2402                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2403                 connect_block(&nodes[3], &Block { header, txdata: vec![node_txn[0].clone()] }, 1);
2404                 check_added_monitors!(nodes[3], 1);
2405
2406                 check_preimage_claim(&nodes[3], &node_txn);
2407         }
2408         get_announce_close_broadcast_events(&nodes, 2, 3);
2409         assert_eq!(nodes[2].node.list_channels().len(), 0);
2410         assert_eq!(nodes[3].node.list_channels().len(), 1);
2411
2412         { // Cheat and reset nodes[4]'s height to 1
2413                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2414                 connect_block(&nodes[4], &Block { header, txdata: vec![] }, 1);
2415         }
2416
2417         assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
2418         assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
2419         // One pending HTLC to time out:
2420         let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2421         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2422         // buffer space).
2423
2424         let (close_chan_update_1, close_chan_update_2) = {
2425                 let mut block = Block {
2426                         header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2427                         txdata: vec![],
2428                 };
2429                 connect_block(&nodes[3], &block, 2);
2430                 for i in 3..TEST_FINAL_CLTV + 2 + LATENCY_GRACE_PERIOD_BLOCKS + 1 {
2431                         block = Block {
2432                                 header: BlockHeader { version: 0x20000000, prev_blockhash: block.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2433                                 txdata: vec![],
2434                         };
2435                         connect_block(&nodes[3], &block, i);
2436                 }
2437                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2438                 assert_eq!(events.len(), 1);
2439                 let close_chan_update_1 = match events[0] {
2440                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2441                                 msg.clone()
2442                         },
2443                         _ => panic!("Unexpected event"),
2444                 };
2445                 check_added_monitors!(nodes[3], 1);
2446
2447                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2448                 {
2449                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2450                         node_txn.retain(|tx| {
2451                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2452                                         false
2453                                 } else { true }
2454                         });
2455                 }
2456
2457                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2458
2459                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2460                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, 3_000_000);
2461
2462                 block = Block {
2463                         header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2464                         txdata: vec![],
2465                 };
2466
2467                 connect_block(&nodes[4], &block, 2);
2468                 for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
2469                         block = Block {
2470                                 header: BlockHeader { version: 0x20000000, prev_blockhash: block.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2471                                 txdata: vec![],
2472                         };
2473                         connect_block(&nodes[4], &block, i);
2474                 }
2475                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2476                 assert_eq!(events.len(), 1);
2477                 let close_chan_update_2 = match events[0] {
2478                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2479                                 msg.clone()
2480                         },
2481                         _ => panic!("Unexpected event"),
2482                 };
2483                 check_added_monitors!(nodes[4], 1);
2484                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2485
2486                 block = Block {
2487                         header: BlockHeader { version: 0x20000000, prev_blockhash: block.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2488                         txdata: vec![node_txn[0].clone()],
2489                 };
2490                 connect_block(&nodes[4], &block, TEST_FINAL_CLTV - 5);
2491
2492                 check_preimage_claim(&nodes[4], &node_txn);
2493                 (close_chan_update_1, close_chan_update_2)
2494         };
2495         nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2496         nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2497         assert_eq!(nodes[3].node.list_channels().len(), 0);
2498         assert_eq!(nodes[4].node.list_channels().len(), 0);
2499 }
2500
2501 #[test]
2502 fn test_justice_tx() {
2503         // Test justice txn built on revoked HTLC-Success tx, against both sides
2504         let mut alice_config = UserConfig::default();
2505         alice_config.channel_options.announced_channel = true;
2506         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2507         alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2508         let mut bob_config = UserConfig::default();
2509         bob_config.channel_options.announced_channel = true;
2510         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2511         bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2512         let user_cfgs = [Some(alice_config), Some(bob_config)];
2513         let chanmon_cfgs = create_chanmon_cfgs(2);
2514         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2515         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2516         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2517         // Create some new channels:
2518         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2519
2520         // A pending HTLC which will be revoked:
2521         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2522         // Get the will-be-revoked local txn from nodes[0]
2523         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2524         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2525         assert_eq!(revoked_local_txn[0].input.len(), 1);
2526         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2527         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2528         assert_eq!(revoked_local_txn[1].input.len(), 1);
2529         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2530         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2531         // Revoke the old state
2532         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 3_000_000);
2533
2534         {
2535                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2536                 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2537                 {
2538                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2539                         assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2540                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2541
2542                         check_spends!(node_txn[0], revoked_local_txn[0]);
2543                         node_txn.swap_remove(0);
2544                         node_txn.truncate(1);
2545                 }
2546                 check_added_monitors!(nodes[1], 1);
2547                 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2548
2549                 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2550                 // Verify broadcast of revoked HTLC-timeout
2551                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2552                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2553                 check_added_monitors!(nodes[0], 1);
2554                 // Broadcast revoked HTLC-timeout on node 1
2555                 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2556                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2557         }
2558         get_announce_close_broadcast_events(&nodes, 0, 1);
2559
2560         assert_eq!(nodes[0].node.list_channels().len(), 0);
2561         assert_eq!(nodes[1].node.list_channels().len(), 0);
2562
2563         // We test justice_tx build by A on B's revoked HTLC-Success tx
2564         // Create some new channels:
2565         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2566         {
2567                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2568                 node_txn.clear();
2569         }
2570
2571         // A pending HTLC which will be revoked:
2572         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2573         // Get the will-be-revoked local txn from B
2574         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2575         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2576         assert_eq!(revoked_local_txn[0].input.len(), 1);
2577         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2578         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2579         // Revoke the old state
2580         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4, 3_000_000);
2581         {
2582                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2583                 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2584                 {
2585                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2586                         assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2587                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2588
2589                         check_spends!(node_txn[0], revoked_local_txn[0]);
2590                         node_txn.swap_remove(0);
2591                 }
2592                 check_added_monitors!(nodes[0], 1);
2593                 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2594
2595                 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2596                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2597                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2598                 check_added_monitors!(nodes[1], 1);
2599                 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2600                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2601         }
2602         get_announce_close_broadcast_events(&nodes, 0, 1);
2603         assert_eq!(nodes[0].node.list_channels().len(), 0);
2604         assert_eq!(nodes[1].node.list_channels().len(), 0);
2605 }
2606
2607 #[test]
2608 fn revoked_output_claim() {
2609         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2610         // transaction is broadcast by its counterparty
2611         let chanmon_cfgs = create_chanmon_cfgs(2);
2612         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2613         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2614         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2615         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2616         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2617         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2618         assert_eq!(revoked_local_txn.len(), 1);
2619         // Only output is the full channel value back to nodes[0]:
2620         assert_eq!(revoked_local_txn[0].output.len(), 1);
2621         // Send a payment through, updating everyone's latest commitment txn
2622         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000, 5_000_000);
2623
2624         // Inform nodes[1] that nodes[0] broadcast a stale tx
2625         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2626         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2627         check_added_monitors!(nodes[1], 1);
2628         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2629         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2630
2631         check_spends!(node_txn[0], revoked_local_txn[0]);
2632         check_spends!(node_txn[1], chan_1.3);
2633
2634         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2635         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2636         get_announce_close_broadcast_events(&nodes, 0, 1);
2637         check_added_monitors!(nodes[0], 1)
2638 }
2639
2640 #[test]
2641 fn claim_htlc_outputs_shared_tx() {
2642         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2643         let chanmon_cfgs = create_chanmon_cfgs(2);
2644         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2645         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2646         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2647
2648         // Create some new channel:
2649         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2650
2651         // Rebalance the network to generate htlc in the two directions
2652         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2653         // 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
2654         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2655         let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2656
2657         // Get the will-be-revoked local txn from node[0]
2658         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2659         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2660         assert_eq!(revoked_local_txn[0].input.len(), 1);
2661         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2662         assert_eq!(revoked_local_txn[1].input.len(), 1);
2663         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2664         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2665         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2666
2667         //Revoke the old state
2668         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2669
2670         {
2671                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2672                 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2673                 check_added_monitors!(nodes[0], 1);
2674                 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2675                 check_added_monitors!(nodes[1], 1);
2676                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
2677                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2678
2679                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2680                 assert_eq!(node_txn.len(), 3); // ChannelMonitor: penalty tx, ChannelManager: local commitment + HTLC-timeout
2681
2682                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2683                 check_spends!(node_txn[0], revoked_local_txn[0]);
2684
2685                 let mut witness_lens = BTreeSet::new();
2686                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2687                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2688                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2689                 assert_eq!(witness_lens.len(), 3);
2690                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2691                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2692                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2693
2694                 // Next nodes[1] broadcasts its current local tx state:
2695                 assert_eq!(node_txn[1].input.len(), 1);
2696                 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2697
2698                 assert_eq!(node_txn[2].input.len(), 1);
2699                 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
2700                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2701                 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
2702                 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
2703                 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
2704         }
2705         get_announce_close_broadcast_events(&nodes, 0, 1);
2706         assert_eq!(nodes[0].node.list_channels().len(), 0);
2707         assert_eq!(nodes[1].node.list_channels().len(), 0);
2708 }
2709
2710 #[test]
2711 fn claim_htlc_outputs_single_tx() {
2712         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2713         let chanmon_cfgs = create_chanmon_cfgs(2);
2714         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2715         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2716         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2717
2718         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2719
2720         // Rebalance the network to generate htlc in the two directions
2721         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2722         // 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
2723         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2724         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2725         let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2726
2727         // Get the will-be-revoked local txn from node[0]
2728         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2729
2730         //Revoke the old state
2731         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2732
2733         {
2734                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2735                 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2736                 check_added_monitors!(nodes[0], 1);
2737                 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2738                 check_added_monitors!(nodes[1], 1);
2739                 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
2740
2741                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 200, true, header.block_hash());
2742                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2743
2744                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2745                 assert_eq!(node_txn.len(), 9);
2746                 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2747                 // ChannelManager: local commmitment + local HTLC-timeout (2)
2748                 // ChannelMonitor: bumped justice tx, after one increase, bumps on HTLC aren't generated not being substantial anymore, bump on revoked to_local isn't generated due to more room for expiration (2)
2749                 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2750
2751                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2752                 assert_eq!(node_txn[2].input.len(), 1);
2753                 check_spends!(node_txn[2], chan_1.3);
2754                 assert_eq!(node_txn[3].input.len(), 1);
2755                 let witness_script = node_txn[3].input[0].witness.last().unwrap();
2756                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2757                 check_spends!(node_txn[3], node_txn[2]);
2758
2759                 // Justice transactions are indices 1-2-4
2760                 assert_eq!(node_txn[0].input.len(), 1);
2761                 assert_eq!(node_txn[1].input.len(), 1);
2762                 assert_eq!(node_txn[4].input.len(), 1);
2763
2764                 check_spends!(node_txn[0], revoked_local_txn[0]);
2765                 check_spends!(node_txn[1], revoked_local_txn[0]);
2766                 check_spends!(node_txn[4], revoked_local_txn[0]);
2767
2768                 let mut witness_lens = BTreeSet::new();
2769                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2770                 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2771                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2772                 assert_eq!(witness_lens.len(), 3);
2773                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2774                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2775                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2776         }
2777         get_announce_close_broadcast_events(&nodes, 0, 1);
2778         assert_eq!(nodes[0].node.list_channels().len(), 0);
2779         assert_eq!(nodes[1].node.list_channels().len(), 0);
2780 }
2781
2782 #[test]
2783 fn test_htlc_on_chain_success() {
2784         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2785         // the preimage backward accordingly. So here we test that ChannelManager is
2786         // broadcasting the right event to other nodes in payment path.
2787         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2788         // A --------------------> B ----------------------> C (preimage)
2789         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2790         // commitment transaction was broadcast.
2791         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2792         // towards B.
2793         // B should be able to claim via preimage if A then broadcasts its local tx.
2794         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2795         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2796         // PaymentSent event).
2797
2798         let chanmon_cfgs = create_chanmon_cfgs(3);
2799         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2800         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2801         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2802
2803         // Create some initial channels
2804         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2805         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2806
2807         // Rebalance the network a bit by relaying one payment through all the channels...
2808         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2809         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2810
2811         let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2812         let (our_payment_preimage_2, _payment_hash_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2813         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2814
2815         // Broadcast legit commitment tx from C on B's chain
2816         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2817         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2818         assert_eq!(commitment_tx.len(), 1);
2819         check_spends!(commitment_tx[0], chan_2.3);
2820         nodes[2].node.claim_funds(our_payment_preimage, &None, 3_000_000);
2821         nodes[2].node.claim_funds(our_payment_preimage_2, &None, 3_000_000);
2822         check_added_monitors!(nodes[2], 2);
2823         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2824         assert!(updates.update_add_htlcs.is_empty());
2825         assert!(updates.update_fail_htlcs.is_empty());
2826         assert!(updates.update_fail_malformed_htlcs.is_empty());
2827         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2828
2829         connect_block(&nodes[2], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2830         check_closed_broadcast!(nodes[2], false);
2831         check_added_monitors!(nodes[2], 1);
2832         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)
2833         assert_eq!(node_txn.len(), 5);
2834         assert_eq!(node_txn[0], node_txn[3]);
2835         assert_eq!(node_txn[1], node_txn[4]);
2836         assert_eq!(node_txn[2], commitment_tx[0]);
2837         check_spends!(node_txn[0], commitment_tx[0]);
2838         check_spends!(node_txn[1], commitment_tx[0]);
2839         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2840         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2841         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2842         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2843         assert_eq!(node_txn[0].lock_time, 0);
2844         assert_eq!(node_txn[1].lock_time, 0);
2845
2846         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2847         connect_block(&nodes[1], &Block { header, txdata: node_txn}, 1);
2848         {
2849                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2850                 assert_eq!(added_monitors.len(), 1);
2851                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2852                 added_monitors.clear();
2853         }
2854         let events = nodes[1].node.get_and_clear_pending_msg_events();
2855         {
2856                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2857                 assert_eq!(added_monitors.len(), 2);
2858                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2859                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2860                 added_monitors.clear();
2861         }
2862         assert_eq!(events.len(), 2);
2863         match events[0] {
2864                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2865                 _ => panic!("Unexpected event"),
2866         }
2867         match events[1] {
2868                 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, .. } } => {
2869                         assert!(update_add_htlcs.is_empty());
2870                         assert!(update_fail_htlcs.is_empty());
2871                         assert_eq!(update_fulfill_htlcs.len(), 1);
2872                         assert!(update_fail_malformed_htlcs.is_empty());
2873                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2874                 },
2875                 _ => panic!("Unexpected event"),
2876         };
2877         macro_rules! check_tx_local_broadcast {
2878                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2879                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2880                         assert_eq!(node_txn.len(), 5);
2881                         // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2882                         // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2883                         check_spends!(node_txn[0], $commitment_tx);
2884                         check_spends!(node_txn[1], $commitment_tx);
2885                         assert_ne!(node_txn[0].lock_time, 0);
2886                         assert_ne!(node_txn[1].lock_time, 0);
2887                         if $htlc_offered {
2888                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2889                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2890                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2891                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2892                         } else {
2893                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2894                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2895                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2896                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2897                         }
2898                         check_spends!(node_txn[2], $chan_tx);
2899                         check_spends!(node_txn[3], node_txn[2]);
2900                         check_spends!(node_txn[4], node_txn[2]);
2901                         assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), 71);
2902                         assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2903                         assert_eq!(node_txn[4].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2904                         assert!(node_txn[3].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2905                         assert!(node_txn[4].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2906                         assert_ne!(node_txn[3].lock_time, 0);
2907                         assert_ne!(node_txn[4].lock_time, 0);
2908                         node_txn.clear();
2909                 } }
2910         }
2911         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2912         // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2913         // timeout-claim of the output that nodes[2] just claimed via success.
2914         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2915
2916         // Broadcast legit commitment tx from A on B's chain
2917         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2918         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2919         check_spends!(commitment_tx[0], chan_1.3);
2920         connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2921         check_closed_broadcast!(nodes[1], false);
2922         check_added_monitors!(nodes[1], 1);
2923         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 1 (HTLC-Success)
2924         assert_eq!(node_txn.len(), 4);
2925         check_spends!(node_txn[0], commitment_tx[0]);
2926         assert_eq!(node_txn[0].input.len(), 2);
2927         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2928         assert_eq!(node_txn[0].input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2929         assert_eq!(node_txn[0].lock_time, 0);
2930         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2931         check_spends!(node_txn[1], chan_1.3);
2932         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
2933         check_spends!(node_txn[2], node_txn[1]);
2934         check_spends!(node_txn[3], node_txn[1]);
2935         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2936         // we already checked the same situation with A.
2937
2938         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2939         connect_block(&nodes[0], &Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
2940         check_closed_broadcast!(nodes[0], false);
2941         check_added_monitors!(nodes[0], 1);
2942         let events = nodes[0].node.get_and_clear_pending_events();
2943         assert_eq!(events.len(), 2);
2944         let mut first_claimed = false;
2945         for event in events {
2946                 match event {
2947                         Event::PaymentSent { payment_preimage } => {
2948                                 if payment_preimage == our_payment_preimage {
2949                                         assert!(!first_claimed);
2950                                         first_claimed = true;
2951                                 } else {
2952                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2953                                 }
2954                         },
2955                         _ => panic!("Unexpected event"),
2956                 }
2957         }
2958         check_tx_local_broadcast!(nodes[0], true, commitment_tx[0], chan_1.3);
2959 }
2960
2961 #[test]
2962 fn test_htlc_on_chain_timeout() {
2963         // Test that in case of a unilateral close onchain, we detect the state of output and
2964         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2965         // broadcasting the right event to other nodes in payment path.
2966         // A ------------------> B ----------------------> C (timeout)
2967         //    B's commitment tx                 C's commitment tx
2968         //            \                                  \
2969         //         B's HTLC timeout tx               B's timeout tx
2970
2971         let chanmon_cfgs = create_chanmon_cfgs(3);
2972         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2973         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2974         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2975
2976         // Create some intial channels
2977         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2978         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2979
2980         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2981         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2982         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2983
2984         let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2985         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2986
2987         // Broadcast legit commitment tx from C on B's chain
2988         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2989         check_spends!(commitment_tx[0], chan_2.3);
2990         nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
2991         check_added_monitors!(nodes[2], 0);
2992         expect_pending_htlcs_forwardable!(nodes[2]);
2993         check_added_monitors!(nodes[2], 1);
2994
2995         let events = nodes[2].node.get_and_clear_pending_msg_events();
2996         assert_eq!(events.len(), 1);
2997         match events[0] {
2998                 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, .. } } => {
2999                         assert!(update_add_htlcs.is_empty());
3000                         assert!(!update_fail_htlcs.is_empty());
3001                         assert!(update_fulfill_htlcs.is_empty());
3002                         assert!(update_fail_malformed_htlcs.is_empty());
3003                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
3004                 },
3005                 _ => panic!("Unexpected event"),
3006         };
3007         connect_block(&nodes[2], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
3008         check_closed_broadcast!(nodes[2], false);
3009         check_added_monitors!(nodes[2], 1);
3010         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
3011         assert_eq!(node_txn.len(), 1);
3012         check_spends!(node_txn[0], chan_2.3);
3013         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
3014
3015         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
3016         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
3017         connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
3018         let timeout_tx;
3019         {
3020                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3021                 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
3022                 assert_eq!(node_txn[1], node_txn[3]);
3023                 assert_eq!(node_txn[2], node_txn[4]);
3024
3025                 check_spends!(node_txn[0], commitment_tx[0]);
3026                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3027
3028                 check_spends!(node_txn[1], chan_2.3);
3029                 check_spends!(node_txn[2], node_txn[1]);
3030                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
3031                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3032
3033                 timeout_tx = node_txn[0].clone();
3034                 node_txn.clear();
3035         }
3036
3037         connect_block(&nodes[1], &Block { header, txdata: vec![timeout_tx]}, 1);
3038         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
3039         check_added_monitors!(nodes[1], 1);
3040         check_closed_broadcast!(nodes[1], false);
3041
3042         expect_pending_htlcs_forwardable!(nodes[1]);
3043         check_added_monitors!(nodes[1], 1);
3044         let events = nodes[1].node.get_and_clear_pending_msg_events();
3045         assert_eq!(events.len(), 1);
3046         match events[0] {
3047                 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, .. } } => {
3048                         assert!(update_add_htlcs.is_empty());
3049                         assert!(!update_fail_htlcs.is_empty());
3050                         assert!(update_fulfill_htlcs.is_empty());
3051                         assert!(update_fail_malformed_htlcs.is_empty());
3052                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3053                 },
3054                 _ => panic!("Unexpected event"),
3055         };
3056         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // Well... here we detect our own htlc_timeout_tx so no tx to be generated
3057         assert_eq!(node_txn.len(), 0);
3058
3059         // Broadcast legit commitment tx from B on A's chain
3060         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3061         check_spends!(commitment_tx[0], chan_1.3);
3062
3063         connect_block(&nodes[0], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
3064         check_closed_broadcast!(nodes[0], false);
3065         check_added_monitors!(nodes[0], 1);
3066         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 1 timeout tx
3067         assert_eq!(node_txn.len(), 3);
3068         check_spends!(node_txn[0], commitment_tx[0]);
3069         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3070         check_spends!(node_txn[1], chan_1.3);
3071         check_spends!(node_txn[2], node_txn[1]);
3072         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
3073         assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3074 }
3075
3076 #[test]
3077 fn test_simple_commitment_revoked_fail_backward() {
3078         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3079         // and fail backward accordingly.
3080
3081         let chanmon_cfgs = create_chanmon_cfgs(3);
3082         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3083         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3084         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3085
3086         // Create some initial channels
3087         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3088         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3089
3090         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3091         // Get the will-be-revoked local txn from nodes[2]
3092         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3093         // Revoke the old state
3094         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, 3_000_000);
3095
3096         let (_, payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3097
3098         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
3099         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3100         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
3101         check_added_monitors!(nodes[1], 1);
3102         check_closed_broadcast!(nodes[1], false);
3103
3104         expect_pending_htlcs_forwardable!(nodes[1]);
3105         check_added_monitors!(nodes[1], 1);
3106         let events = nodes[1].node.get_and_clear_pending_msg_events();
3107         assert_eq!(events.len(), 1);
3108         match events[0] {
3109                 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, .. } } => {
3110                         assert!(update_add_htlcs.is_empty());
3111                         assert_eq!(update_fail_htlcs.len(), 1);
3112                         assert!(update_fulfill_htlcs.is_empty());
3113                         assert!(update_fail_malformed_htlcs.is_empty());
3114                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3115
3116                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3117                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3118
3119                         let events = nodes[0].node.get_and_clear_pending_msg_events();
3120                         assert_eq!(events.len(), 1);
3121                         match events[0] {
3122                                 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3123                                 _ => panic!("Unexpected event"),
3124                         }
3125                         expect_payment_failed!(nodes[0], payment_hash, false);
3126                 },
3127                 _ => panic!("Unexpected event"),
3128         }
3129 }
3130
3131 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3132         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3133         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3134         // commitment transaction anymore.
3135         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3136         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3137         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3138         // technically disallowed and we should probably handle it reasonably.
3139         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3140         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3141         // transactions:
3142         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3143         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3144         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3145         //   and once they revoke the previous commitment transaction (allowing us to send a new
3146         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3147         let chanmon_cfgs = create_chanmon_cfgs(3);
3148         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3149         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3150         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3151
3152         // Create some initial channels
3153         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3154         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3155
3156         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3157         // Get the will-be-revoked local txn from nodes[2]
3158         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3159         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3160         // Revoke the old state
3161         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, if no_to_remote { 10_000 } else { 3_000_000});
3162
3163         let value = if use_dust {
3164                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3165                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3166                 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3167         } else { 3000000 };
3168
3169         let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3170         let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3171         let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3172
3173         assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, &None));
3174         expect_pending_htlcs_forwardable!(nodes[2]);
3175         check_added_monitors!(nodes[2], 1);
3176         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3177         assert!(updates.update_add_htlcs.is_empty());
3178         assert!(updates.update_fulfill_htlcs.is_empty());
3179         assert!(updates.update_fail_malformed_htlcs.is_empty());
3180         assert_eq!(updates.update_fail_htlcs.len(), 1);
3181         assert!(updates.update_fee.is_none());
3182         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3183         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3184         // Drop the last RAA from 3 -> 2
3185
3186         assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, &None));
3187         expect_pending_htlcs_forwardable!(nodes[2]);
3188         check_added_monitors!(nodes[2], 1);
3189         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3190         assert!(updates.update_add_htlcs.is_empty());
3191         assert!(updates.update_fulfill_htlcs.is_empty());
3192         assert!(updates.update_fail_malformed_htlcs.is_empty());
3193         assert_eq!(updates.update_fail_htlcs.len(), 1);
3194         assert!(updates.update_fee.is_none());
3195         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3196         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3197         check_added_monitors!(nodes[1], 1);
3198         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3199         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3200         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3201         check_added_monitors!(nodes[2], 1);
3202
3203         assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, &None));
3204         expect_pending_htlcs_forwardable!(nodes[2]);
3205         check_added_monitors!(nodes[2], 1);
3206         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3207         assert!(updates.update_add_htlcs.is_empty());
3208         assert!(updates.update_fulfill_htlcs.is_empty());
3209         assert!(updates.update_fail_malformed_htlcs.is_empty());
3210         assert_eq!(updates.update_fail_htlcs.len(), 1);
3211         assert!(updates.update_fee.is_none());
3212         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3213         // At this point first_payment_hash has dropped out of the latest two commitment
3214         // transactions that nodes[1] is tracking...
3215         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3216         check_added_monitors!(nodes[1], 1);
3217         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3218         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3219         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3220         check_added_monitors!(nodes[2], 1);
3221
3222         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3223         // on nodes[2]'s RAA.
3224         let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3225         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3226         let logger = test_utils::TestLogger::new();
3227         let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3228         nodes[1].node.send_payment(&route, fourth_payment_hash, &None).unwrap();
3229         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3230         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3231         check_added_monitors!(nodes[1], 0);
3232
3233         if deliver_bs_raa {
3234                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3235                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3236                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3237                 check_added_monitors!(nodes[1], 1);
3238                 let events = nodes[1].node.get_and_clear_pending_events();
3239                 assert_eq!(events.len(), 1);
3240                 match events[0] {
3241                         Event::PendingHTLCsForwardable { .. } => { },
3242                         _ => panic!("Unexpected event"),
3243                 };
3244                 // Deliberately don't process the pending fail-back so they all fail back at once after
3245                 // block connection just like the !deliver_bs_raa case
3246         }
3247
3248         let mut failed_htlcs = HashSet::new();
3249         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3250
3251         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
3252         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3253         check_added_monitors!(nodes[1], 1);
3254         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
3255
3256         let events = nodes[1].node.get_and_clear_pending_events();
3257         assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
3258         match events[0] {
3259                 Event::PaymentFailed { ref payment_hash, .. } => {
3260                         assert_eq!(*payment_hash, fourth_payment_hash);
3261                 },
3262                 _ => panic!("Unexpected event"),
3263         }
3264         if !deliver_bs_raa {
3265                 match events[1] {
3266                         Event::PendingHTLCsForwardable { .. } => { },
3267                         _ => panic!("Unexpected event"),
3268                 };
3269         }
3270         nodes[1].node.process_pending_htlc_forwards();
3271         check_added_monitors!(nodes[1], 1);
3272
3273         let events = nodes[1].node.get_and_clear_pending_msg_events();
3274         assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
3275         match events[if deliver_bs_raa { 1 } else { 0 }] {
3276                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3277                 _ => panic!("Unexpected event"),
3278         }
3279         if deliver_bs_raa {
3280                 match events[0] {
3281                         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, .. } } => {
3282                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3283                                 assert_eq!(update_add_htlcs.len(), 1);
3284                                 assert!(update_fulfill_htlcs.is_empty());
3285                                 assert!(update_fail_htlcs.is_empty());
3286                                 assert!(update_fail_malformed_htlcs.is_empty());
3287                         },
3288                         _ => panic!("Unexpected event"),
3289                 }
3290         }
3291         match events[if deliver_bs_raa { 2 } else { 1 }] {
3292                 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, .. } } => {
3293                         assert!(update_add_htlcs.is_empty());
3294                         assert_eq!(update_fail_htlcs.len(), 3);
3295                         assert!(update_fulfill_htlcs.is_empty());
3296                         assert!(update_fail_malformed_htlcs.is_empty());
3297                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3298
3299                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3300                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3301                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3302
3303                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3304
3305                         let events = nodes[0].node.get_and_clear_pending_msg_events();
3306                         // If we delivered B's RAA we got an unknown preimage error, not something
3307                         // that we should update our routing table for.
3308                         assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
3309                         for event in events {
3310                                 match event {
3311                                         MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3312                                         _ => panic!("Unexpected event"),
3313                                 }
3314                         }
3315                         let events = nodes[0].node.get_and_clear_pending_events();
3316                         assert_eq!(events.len(), 3);
3317                         match events[0] {
3318                                 Event::PaymentFailed { ref payment_hash, .. } => {
3319                                         assert!(failed_htlcs.insert(payment_hash.0));
3320                                 },
3321                                 _ => panic!("Unexpected event"),
3322                         }
3323                         match events[1] {
3324                                 Event::PaymentFailed { ref payment_hash, .. } => {
3325                                         assert!(failed_htlcs.insert(payment_hash.0));
3326                                 },
3327                                 _ => panic!("Unexpected event"),
3328                         }
3329                         match events[2] {
3330                                 Event::PaymentFailed { ref payment_hash, .. } => {
3331                                         assert!(failed_htlcs.insert(payment_hash.0));
3332                                 },
3333                                 _ => panic!("Unexpected event"),
3334                         }
3335                 },
3336                 _ => panic!("Unexpected event"),
3337         }
3338
3339         assert!(failed_htlcs.contains(&first_payment_hash.0));
3340         assert!(failed_htlcs.contains(&second_payment_hash.0));
3341         assert!(failed_htlcs.contains(&third_payment_hash.0));
3342 }
3343
3344 #[test]
3345 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3346         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3347         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3348         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3349         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3350 }
3351
3352 #[test]
3353 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3354         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3355         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3356         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3357         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3358 }
3359
3360 #[test]
3361 fn fail_backward_pending_htlc_upon_channel_failure() {
3362         let chanmon_cfgs = create_chanmon_cfgs(2);
3363         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3364         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3365         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3366         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3367         let logger = test_utils::TestLogger::new();
3368
3369         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3370         {
3371                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
3372                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3373                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3374                 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
3375                 check_added_monitors!(nodes[0], 1);
3376
3377                 let payment_event = {
3378                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3379                         assert_eq!(events.len(), 1);
3380                         SendEvent::from_event(events.remove(0))
3381                 };
3382                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3383                 assert_eq!(payment_event.msgs.len(), 1);
3384         }
3385
3386         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3387         let (_, failed_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3388         {
3389                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3390                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3391                 nodes[0].node.send_payment(&route, failed_payment_hash, &None).unwrap();
3392                 check_added_monitors!(nodes[0], 0);
3393
3394                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3395         }
3396
3397         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3398         {
3399                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[1]);
3400
3401                 let secp_ctx = Secp256k1::new();
3402                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3403                 let current_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
3404                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3405                 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3406                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &None, current_height).unwrap();
3407                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3408                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3409
3410                 // Send a 0-msat update_add_htlc to fail the channel.
3411                 let update_add_htlc = msgs::UpdateAddHTLC {
3412                         channel_id: chan.2,
3413                         htlc_id: 0,
3414                         amount_msat: 0,
3415                         payment_hash,
3416                         cltv_expiry,
3417                         onion_routing_packet,
3418                 };
3419                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3420         }
3421
3422         // Check that Alice fails backward the pending HTLC from the second payment.
3423         expect_payment_failed!(nodes[0], failed_payment_hash, true);
3424         check_closed_broadcast!(nodes[0], true);
3425         check_added_monitors!(nodes[0], 1);
3426 }
3427
3428 #[test]
3429 fn test_htlc_ignore_latest_remote_commitment() {
3430         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3431         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3432         let chanmon_cfgs = create_chanmon_cfgs(2);
3433         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3434         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3435         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3436         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3437
3438         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3439         nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
3440         check_closed_broadcast!(nodes[0], false);
3441         check_added_monitors!(nodes[0], 1);
3442
3443         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3444         assert_eq!(node_txn.len(), 2);
3445
3446         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3447         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3448         check_closed_broadcast!(nodes[1], false);
3449         check_added_monitors!(nodes[1], 1);
3450
3451         // Duplicate the connect_block call since this may happen due to other listeners
3452         // registering new transactions
3453         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3454 }
3455
3456 #[test]
3457 fn test_force_close_fail_back() {
3458         // Check which HTLCs are failed-backwards on channel force-closure
3459         let chanmon_cfgs = create_chanmon_cfgs(3);
3460         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3461         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3462         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3463         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3464         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3465         let logger = test_utils::TestLogger::new();
3466
3467         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3468
3469         let mut payment_event = {
3470                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3471                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, 42, &logger).unwrap();
3472                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
3473                 check_added_monitors!(nodes[0], 1);
3474
3475                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3476                 assert_eq!(events.len(), 1);
3477                 SendEvent::from_event(events.remove(0))
3478         };
3479
3480         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3481         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3482
3483         expect_pending_htlcs_forwardable!(nodes[1]);
3484
3485         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3486         assert_eq!(events_2.len(), 1);
3487         payment_event = SendEvent::from_event(events_2.remove(0));
3488         assert_eq!(payment_event.msgs.len(), 1);
3489
3490         check_added_monitors!(nodes[1], 1);
3491         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3492         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3493         check_added_monitors!(nodes[2], 1);
3494         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3495
3496         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3497         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3498         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3499
3500         nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
3501         check_closed_broadcast!(nodes[2], false);
3502         check_added_monitors!(nodes[2], 1);
3503         let tx = {
3504                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3505                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3506                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3507                 // back to nodes[1] upon timeout otherwise.
3508                 assert_eq!(node_txn.len(), 1);
3509                 node_txn.remove(0)
3510         };
3511
3512         let block = Block {
3513                 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
3514                 txdata: vec![tx.clone()],
3515         };
3516         connect_block(&nodes[1], &block, 1);
3517
3518         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3519         check_closed_broadcast!(nodes[1], false);
3520         check_added_monitors!(nodes[1], 1);
3521
3522         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3523         {
3524                 let mut monitors = nodes[2].chain_monitor.chain_monitor.monitors.lock().unwrap();
3525                 monitors.get_mut(&OutPoint{ txid: Txid::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), index: 0 }).unwrap()
3526                         .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
3527         }
3528         connect_block(&nodes[2], &block, 1);
3529         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3530         assert_eq!(node_txn.len(), 1);
3531         assert_eq!(node_txn[0].input.len(), 1);
3532         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3533         assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3534         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3535
3536         check_spends!(node_txn[0], tx);
3537 }
3538
3539 #[test]
3540 fn test_unconf_chan() {
3541         // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
3542         let chanmon_cfgs = create_chanmon_cfgs(2);
3543         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3544         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3545         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3546         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3547
3548         let channel_state = nodes[0].node.channel_state.lock().unwrap();
3549         assert_eq!(channel_state.by_id.len(), 1);
3550         assert_eq!(channel_state.short_to_id.len(), 1);
3551         mem::drop(channel_state);
3552
3553         let mut headers = Vec::new();
3554         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3555         headers.push(header.clone());
3556         for _i in 2..100 {
3557                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3558                 headers.push(header.clone());
3559         }
3560         while !headers.is_empty() {
3561                 nodes[0].node.block_disconnected(&headers.pop().unwrap());
3562         }
3563         check_closed_broadcast!(nodes[0], false);
3564         check_added_monitors!(nodes[0], 1);
3565         let channel_state = nodes[0].node.channel_state.lock().unwrap();
3566         assert_eq!(channel_state.by_id.len(), 0);
3567         assert_eq!(channel_state.short_to_id.len(), 0);
3568 }
3569
3570 #[test]
3571 fn test_simple_peer_disconnect() {
3572         // Test that we can reconnect when there are no lost messages
3573         let chanmon_cfgs = create_chanmon_cfgs(3);
3574         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3575         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3576         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3577         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3578         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3579
3580         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3581         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3582         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3583
3584         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3585         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3586         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3587         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1, 1_000_000);
3588
3589         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3590         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3591         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3592
3593         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3594         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3595         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3596         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3597
3598         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3599         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3600
3601         claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3, 1_000_000);
3602         fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
3603
3604         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3605         {
3606                 let events = nodes[0].node.get_and_clear_pending_events();
3607                 assert_eq!(events.len(), 2);
3608                 match events[0] {
3609                         Event::PaymentSent { payment_preimage } => {
3610                                 assert_eq!(payment_preimage, payment_preimage_3);
3611                         },
3612                         _ => panic!("Unexpected event"),
3613                 }
3614                 match events[1] {
3615                         Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
3616                                 assert_eq!(payment_hash, payment_hash_5);
3617                                 assert!(rejected_by_dest);
3618                         },
3619                         _ => panic!("Unexpected event"),
3620                 }
3621         }
3622
3623         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4, 1_000_000);
3624         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3625 }
3626
3627 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
3628         // Test that we can reconnect when in-flight HTLC updates get dropped
3629         let chanmon_cfgs = create_chanmon_cfgs(2);
3630         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3631         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3632         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3633         if messages_delivered == 0 {
3634                 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3635                 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3636         } else {
3637                 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3638         }
3639
3640         let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
3641
3642         let logger = test_utils::TestLogger::new();
3643         let payment_event = {
3644                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3645                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3646                         &nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3647                         &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3648                 nodes[0].node.send_payment(&route, payment_hash_1, &None).unwrap();
3649                 check_added_monitors!(nodes[0], 1);
3650
3651                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3652                 assert_eq!(events.len(), 1);
3653                 SendEvent::from_event(events.remove(0))
3654         };
3655         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3656
3657         if messages_delivered < 2 {
3658                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3659         } else {
3660                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3661                 if messages_delivered >= 3 {
3662                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3663                         check_added_monitors!(nodes[1], 1);
3664                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3665
3666                         if messages_delivered >= 4 {
3667                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3668                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3669                                 check_added_monitors!(nodes[0], 1);
3670
3671                                 if messages_delivered >= 5 {
3672                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3673                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3674                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3675                                         check_added_monitors!(nodes[0], 1);
3676
3677                                         if messages_delivered >= 6 {
3678                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3679                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3680                                                 check_added_monitors!(nodes[1], 1);
3681                                         }
3682                                 }
3683                         }
3684                 }
3685         }
3686
3687         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3688         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3689         if messages_delivered < 3 {
3690                 // Even if the funding_locked messages get exchanged, as long as nothing further was
3691                 // received on either side, both sides will need to resend them.
3692                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
3693         } else if messages_delivered == 3 {
3694                 // nodes[0] still wants its RAA + commitment_signed
3695                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
3696         } else if messages_delivered == 4 {
3697                 // nodes[0] still wants its commitment_signed
3698                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3699         } else if messages_delivered == 5 {
3700                 // nodes[1] still wants its final RAA
3701                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3702         } else if messages_delivered == 6 {
3703                 // Everything was delivered...
3704                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3705         }
3706
3707         let events_1 = nodes[1].node.get_and_clear_pending_events();
3708         assert_eq!(events_1.len(), 1);
3709         match events_1[0] {
3710                 Event::PendingHTLCsForwardable { .. } => { },
3711                 _ => panic!("Unexpected event"),
3712         };
3713
3714         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3715         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3716         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3717
3718         nodes[1].node.process_pending_htlc_forwards();
3719
3720         let events_2 = nodes[1].node.get_and_clear_pending_events();
3721         assert_eq!(events_2.len(), 1);
3722         match events_2[0] {
3723                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
3724                         assert_eq!(payment_hash_1, *payment_hash);
3725                         assert_eq!(*payment_secret, None);
3726                         assert_eq!(amt, 1000000);
3727                 },
3728                 _ => panic!("Unexpected event"),
3729         }
3730
3731         nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000);
3732         check_added_monitors!(nodes[1], 1);
3733
3734         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3735         assert_eq!(events_3.len(), 1);
3736         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3737                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3738                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3739                         assert!(updates.update_add_htlcs.is_empty());
3740                         assert!(updates.update_fail_htlcs.is_empty());
3741                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3742                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3743                         assert!(updates.update_fee.is_none());
3744                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3745                 },
3746                 _ => panic!("Unexpected event"),
3747         };
3748
3749         if messages_delivered >= 1 {
3750                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3751
3752                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3753                 assert_eq!(events_4.len(), 1);
3754                 match events_4[0] {
3755                         Event::PaymentSent { ref payment_preimage } => {
3756                                 assert_eq!(payment_preimage_1, *payment_preimage);
3757                         },
3758                         _ => panic!("Unexpected event"),
3759                 }
3760
3761                 if messages_delivered >= 2 {
3762                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3763                         check_added_monitors!(nodes[0], 1);
3764                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3765
3766                         if messages_delivered >= 3 {
3767                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3768                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3769                                 check_added_monitors!(nodes[1], 1);
3770
3771                                 if messages_delivered >= 4 {
3772                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3773                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3774                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3775                                         check_added_monitors!(nodes[1], 1);
3776
3777                                         if messages_delivered >= 5 {
3778                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3779                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3780                                                 check_added_monitors!(nodes[0], 1);
3781                                         }
3782                                 }
3783                         }
3784                 }
3785         }
3786
3787         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3788         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3789         if messages_delivered < 2 {
3790                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
3791                 //TODO: Deduplicate PaymentSent events, then enable this if:
3792                 //if messages_delivered < 1 {
3793                         let events_4 = nodes[0].node.get_and_clear_pending_events();
3794                         assert_eq!(events_4.len(), 1);
3795                         match events_4[0] {
3796                                 Event::PaymentSent { ref payment_preimage } => {
3797                                         assert_eq!(payment_preimage_1, *payment_preimage);
3798                                 },
3799                                 _ => panic!("Unexpected event"),
3800                         }
3801                 //}
3802         } else if messages_delivered == 2 {
3803                 // nodes[0] still wants its RAA + commitment_signed
3804                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
3805         } else if messages_delivered == 3 {
3806                 // nodes[0] still wants its commitment_signed
3807                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
3808         } else if messages_delivered == 4 {
3809                 // nodes[1] still wants its final RAA
3810                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3811         } else if messages_delivered == 5 {
3812                 // Everything was delivered...
3813                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3814         }
3815
3816         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3817         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3818         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3819
3820         // Channel should still work fine...
3821         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3822         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3823                 &nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3824                 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3825         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3826         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3827 }
3828
3829 #[test]
3830 fn test_drop_messages_peer_disconnect_a() {
3831         do_test_drop_messages_peer_disconnect(0);
3832         do_test_drop_messages_peer_disconnect(1);
3833         do_test_drop_messages_peer_disconnect(2);
3834         do_test_drop_messages_peer_disconnect(3);
3835 }
3836
3837 #[test]
3838 fn test_drop_messages_peer_disconnect_b() {
3839         do_test_drop_messages_peer_disconnect(4);
3840         do_test_drop_messages_peer_disconnect(5);
3841         do_test_drop_messages_peer_disconnect(6);
3842 }
3843
3844 #[test]
3845 fn test_funding_peer_disconnect() {
3846         // Test that we can lock in our funding tx while disconnected
3847         let chanmon_cfgs = create_chanmon_cfgs(2);
3848         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3849         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3850         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3851         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3852
3853         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3854         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3855
3856         confirm_transaction(&nodes[0], &tx);
3857         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3858         assert_eq!(events_1.len(), 1);
3859         match events_1[0] {
3860                 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3861                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3862                 },
3863                 _ => panic!("Unexpected event"),
3864         }
3865
3866         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3867
3868         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3869         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3870
3871         confirm_transaction(&nodes[1], &tx);
3872         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3873         assert_eq!(events_2.len(), 2);
3874         let funding_locked = match events_2[0] {
3875                 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3876                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3877                         msg.clone()
3878                 },
3879                 _ => panic!("Unexpected event"),
3880         };
3881         let bs_announcement_sigs = match events_2[1] {
3882                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3883                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3884                         msg.clone()
3885                 },
3886                 _ => panic!("Unexpected event"),
3887         };
3888
3889         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3890
3891         nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3892         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3893         let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3894         assert_eq!(events_3.len(), 2);
3895         let as_announcement_sigs = match events_3[0] {
3896                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3897                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3898                         msg.clone()
3899                 },
3900                 _ => panic!("Unexpected event"),
3901         };
3902         let (as_announcement, as_update) = match events_3[1] {
3903                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3904                         (msg.clone(), update_msg.clone())
3905                 },
3906                 _ => panic!("Unexpected event"),
3907         };
3908
3909         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3910         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3911         assert_eq!(events_4.len(), 1);
3912         let (_, bs_update) = match events_4[0] {
3913                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3914                         (msg.clone(), update_msg.clone())
3915                 },
3916                 _ => panic!("Unexpected event"),
3917         };
3918
3919         nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3920         nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3921         nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3922
3923         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3924         let logger = test_utils::TestLogger::new();
3925         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3926         let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3927         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage, 1_000_000);
3928 }
3929
3930 #[test]
3931 fn test_drop_messages_peer_disconnect_dual_htlc() {
3932         // Test that we can handle reconnecting when both sides of a channel have pending
3933         // commitment_updates when we disconnect.
3934         let chanmon_cfgs = create_chanmon_cfgs(2);
3935         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3936         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3937         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3938         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3939         let logger = test_utils::TestLogger::new();
3940
3941         let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3942
3943         // Now try to send a second payment which will fail to send
3944         let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
3945         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3946         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3947         nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
3948         check_added_monitors!(nodes[0], 1);
3949
3950         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3951         assert_eq!(events_1.len(), 1);
3952         match events_1[0] {
3953                 MessageSendEvent::UpdateHTLCs { .. } => {},
3954                 _ => panic!("Unexpected event"),
3955         }
3956
3957         assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000));
3958         check_added_monitors!(nodes[1], 1);
3959
3960         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3961         assert_eq!(events_2.len(), 1);
3962         match events_2[0] {
3963                 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 } } => {
3964                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3965                         assert!(update_add_htlcs.is_empty());
3966                         assert_eq!(update_fulfill_htlcs.len(), 1);
3967                         assert!(update_fail_htlcs.is_empty());
3968                         assert!(update_fail_malformed_htlcs.is_empty());
3969                         assert!(update_fee.is_none());
3970
3971                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3972                         let events_3 = nodes[0].node.get_and_clear_pending_events();
3973                         assert_eq!(events_3.len(), 1);
3974                         match events_3[0] {
3975                                 Event::PaymentSent { ref payment_preimage } => {
3976                                         assert_eq!(*payment_preimage, payment_preimage_1);
3977                                 },
3978                                 _ => panic!("Unexpected event"),
3979                         }
3980
3981                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3982                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3983                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3984                         check_added_monitors!(nodes[0], 1);
3985                 },
3986                 _ => panic!("Unexpected event"),
3987         }
3988
3989         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3990         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3991
3992         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3993         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3994         assert_eq!(reestablish_1.len(), 1);
3995         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3996         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3997         assert_eq!(reestablish_2.len(), 1);
3998
3999         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4000         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4001         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4002         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4003
4004         assert!(as_resp.0.is_none());
4005         assert!(bs_resp.0.is_none());
4006
4007         assert!(bs_resp.1.is_none());
4008         assert!(bs_resp.2.is_none());
4009
4010         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4011
4012         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4013         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4014         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4015         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4016         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4017         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4018         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4019         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4020         // No commitment_signed so get_event_msg's assert(len == 1) passes
4021         check_added_monitors!(nodes[1], 1);
4022
4023         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4024         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4025         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4026         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4027         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4028         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4029         assert!(bs_second_commitment_signed.update_fee.is_none());
4030         check_added_monitors!(nodes[1], 1);
4031
4032         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4033         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4034         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4035         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4036         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4037         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4038         assert!(as_commitment_signed.update_fee.is_none());
4039         check_added_monitors!(nodes[0], 1);
4040
4041         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4042         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4043         // No commitment_signed so get_event_msg's assert(len == 1) passes
4044         check_added_monitors!(nodes[0], 1);
4045
4046         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4047         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4048         // No commitment_signed so get_event_msg's assert(len == 1) passes
4049         check_added_monitors!(nodes[1], 1);
4050
4051         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4052         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4053         check_added_monitors!(nodes[1], 1);
4054
4055         expect_pending_htlcs_forwardable!(nodes[1]);
4056
4057         let events_5 = nodes[1].node.get_and_clear_pending_events();
4058         assert_eq!(events_5.len(), 1);
4059         match events_5[0] {
4060                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt: _ } => {
4061                         assert_eq!(payment_hash_2, *payment_hash);
4062                         assert_eq!(*payment_secret, None);
4063                 },
4064                 _ => panic!("Unexpected event"),
4065         }
4066
4067         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4068         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4069         check_added_monitors!(nodes[0], 1);
4070
4071         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
4072 }
4073
4074 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4075         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4076         // to avoid our counterparty failing the channel.
4077         let chanmon_cfgs = create_chanmon_cfgs(2);
4078         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4079         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4080         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4081
4082         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4083         let logger = test_utils::TestLogger::new();
4084
4085         let our_payment_hash = if send_partial_mpp {
4086                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4087                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
4088                 let (_, our_payment_hash) = get_payment_preimage_hash!(&nodes[0]);
4089                 let payment_secret = PaymentSecret([0xdb; 32]);
4090                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4091                 // indicates there are more HTLCs coming.
4092                 nodes[0].node.send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200000, CHAN_CONFIRM_DEPTH).unwrap();
4093                 check_added_monitors!(nodes[0], 1);
4094                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4095                 assert_eq!(events.len(), 1);
4096                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4097                 // hop should *not* yet generate any PaymentReceived event(s).
4098                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false);
4099                 our_payment_hash
4100         } else {
4101                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4102         };
4103
4104         let mut block = Block {
4105                 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4106                 txdata: vec![],
4107         };
4108         connect_block(&nodes[0], &block, 101);
4109         connect_block(&nodes[1], &block, 101);
4110         for i in 102..TEST_FINAL_CLTV + 100 + 1 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
4111                 block.header.prev_blockhash = block.block_hash();
4112                 connect_block(&nodes[0], &block, i);
4113                 connect_block(&nodes[1], &block, i);
4114         }
4115
4116         expect_pending_htlcs_forwardable!(nodes[1]);
4117
4118         check_added_monitors!(nodes[1], 1);
4119         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4120         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4121         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4122         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4123         assert!(htlc_timeout_updates.update_fee.is_none());
4124
4125         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4126         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4127         // 100_000 msat as u64, followed by a height of 123 as u32
4128         let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4129         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(123));
4130         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4131 }
4132
4133 #[test]
4134 fn test_htlc_timeout() {
4135         do_test_htlc_timeout(true);
4136         do_test_htlc_timeout(false);
4137 }
4138
4139 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4140         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4141         let chanmon_cfgs = create_chanmon_cfgs(3);
4142         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4143         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4144         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4145         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4146         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4147         let logger = test_utils::TestLogger::new();
4148
4149         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4150         let (_, first_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4151         {
4152                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4153                 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
4154                 nodes[1].node.send_payment(&route, first_payment_hash, &None).unwrap();
4155         }
4156         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4157         check_added_monitors!(nodes[1], 1);
4158
4159         // Now attempt to route a second payment, which should be placed in the holding cell
4160         let (_, second_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4161         if forwarded_htlc {
4162                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4163                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
4164                 nodes[0].node.send_payment(&route, second_payment_hash, &None).unwrap();
4165                 check_added_monitors!(nodes[0], 1);
4166                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4167                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4168                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4169                 expect_pending_htlcs_forwardable!(nodes[1]);
4170                 check_added_monitors!(nodes[1], 0);
4171         } else {
4172                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4173                 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
4174                 nodes[1].node.send_payment(&route, second_payment_hash, &None).unwrap();
4175                 check_added_monitors!(nodes[1], 0);
4176         }
4177
4178         let mut block = Block {
4179                 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4180                 txdata: vec![],
4181         };
4182         connect_block(&nodes[1], &block, 101);
4183         for i in 102..TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
4184                 block.header.prev_blockhash = block.block_hash();
4185                 connect_block(&nodes[1], &block, i);
4186         }
4187
4188         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4189         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4190
4191         block.header.prev_blockhash = block.block_hash();
4192         connect_block(&nodes[1], &block, TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS);
4193
4194         if forwarded_htlc {
4195                 expect_pending_htlcs_forwardable!(nodes[1]);
4196                 check_added_monitors!(nodes[1], 1);
4197                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4198                 assert_eq!(fail_commit.len(), 1);
4199                 match fail_commit[0] {
4200                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4201                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4202                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4203                         },
4204                         _ => unreachable!(),
4205                 }
4206                 expect_payment_failed!(nodes[0], second_payment_hash, false);
4207                 if let &MessageSendEvent::PaymentFailureNetworkUpdate { ref update } = &nodes[0].node.get_and_clear_pending_msg_events()[0] {
4208                         match update {
4209                                 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {},
4210                                 _ => panic!("Unexpected event"),
4211                         }
4212                 } else {
4213                         panic!("Unexpected event");
4214                 }
4215         } else {
4216                 expect_payment_failed!(nodes[1], second_payment_hash, true);
4217         }
4218 }
4219
4220 #[test]
4221 fn test_holding_cell_htlc_add_timeouts() {
4222         do_test_holding_cell_htlc_add_timeouts(false);
4223         do_test_holding_cell_htlc_add_timeouts(true);
4224 }
4225
4226 #[test]
4227 fn test_invalid_channel_announcement() {
4228         //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
4229         let secp_ctx = Secp256k1::new();
4230         let chanmon_cfgs = create_chanmon_cfgs(2);
4231         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4232         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4233         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4234
4235         let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
4236
4237         let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
4238         let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
4239         let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4240         let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4241
4242         nodes[0].net_graph_msg_handler.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id : as_chan.get_short_channel_id().unwrap(), is_permanent: false } );
4243
4244         let as_bitcoin_key = as_chan.get_keys().inner.holder_channel_pubkeys.funding_pubkey;
4245         let bs_bitcoin_key = bs_chan.get_keys().inner.holder_channel_pubkeys.funding_pubkey;
4246
4247         let as_network_key = nodes[0].node.get_our_node_id();
4248         let bs_network_key = nodes[1].node.get_our_node_id();
4249
4250         let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
4251
4252         let mut chan_announcement;
4253
4254         macro_rules! dummy_unsigned_msg {
4255                 () => {
4256                         msgs::UnsignedChannelAnnouncement {
4257                                 features: ChannelFeatures::known(),
4258                                 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4259                                 short_channel_id: as_chan.get_short_channel_id().unwrap(),
4260                                 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
4261                                 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
4262                                 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
4263                                 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
4264                                 excess_data: Vec::new(),
4265                         };
4266                 }
4267         }
4268
4269         macro_rules! sign_msg {
4270                 ($unsigned_msg: expr) => {
4271                         let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
4272                         let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_keys().inner.funding_key);
4273                         let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_keys().inner.funding_key);
4274                         let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
4275                         let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
4276                         chan_announcement = msgs::ChannelAnnouncement {
4277                                 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
4278                                 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
4279                                 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
4280                                 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
4281                                 contents: $unsigned_msg
4282                         }
4283                 }
4284         }
4285
4286         let unsigned_msg = dummy_unsigned_msg!();
4287         sign_msg!(unsigned_msg);
4288         assert_eq!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap(), true);
4289         let _ = nodes[0].net_graph_msg_handler.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id : as_chan.get_short_channel_id().unwrap(), is_permanent: false } );
4290
4291         // Configured with Network::Testnet
4292         let mut unsigned_msg = dummy_unsigned_msg!();
4293         unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.block_hash();
4294         sign_msg!(unsigned_msg);
4295         assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4296
4297         let mut unsigned_msg = dummy_unsigned_msg!();
4298         unsigned_msg.chain_hash = BlockHash::hash(&[1,2,3,4,5,6,7,8,9]);
4299         sign_msg!(unsigned_msg);
4300         assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4301 }
4302
4303 #[test]
4304 fn test_no_txn_manager_serialize_deserialize() {
4305         let chanmon_cfgs = create_chanmon_cfgs(2);
4306         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4307         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4308         let logger: test_utils::TestLogger;
4309         let fee_estimator: test_utils::TestFeeEstimator;
4310         let persister: test_utils::TestPersister;
4311         let new_chain_monitor: test_utils::TestChainMonitor;
4312         let keys_manager: test_utils::TestKeysInterface;
4313         let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4314         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4315
4316         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4317
4318         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4319
4320         let nodes_0_serialized = nodes[0].node.encode();
4321         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4322         nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
4323
4324         logger = test_utils::TestLogger::new();
4325         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4326         persister = test_utils::TestPersister{};
4327         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister);
4328         nodes[0].chain_monitor = &new_chain_monitor;
4329         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4330         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read).unwrap();
4331         assert!(chan_0_monitor_read.is_empty());
4332
4333         let mut nodes_0_read = &nodes_0_serialized[..];
4334         let config = UserConfig::default();
4335         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4336         let (_, nodes_0_deserialized_tmp) = {
4337                 let mut channel_monitors = HashMap::new();
4338                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4339                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4340                         default_config: config,
4341                         keys_manager: &keys_manager,
4342                         fee_estimator: &fee_estimator,
4343                         chain_monitor: nodes[0].chain_monitor,
4344                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4345                         logger: &logger,
4346                         channel_monitors,
4347                 }).unwrap()
4348         };
4349         nodes_0_deserialized = nodes_0_deserialized_tmp;
4350         assert!(nodes_0_read.is_empty());
4351
4352         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4353         nodes[0].node = &nodes_0_deserialized;
4354         assert_eq!(nodes[0].node.list_channels().len(), 1);
4355         check_added_monitors!(nodes[0], 1);
4356
4357         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4358         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4359         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4360         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4361
4362         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4363         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4364         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4365         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4366
4367         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4368         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4369         for node in nodes.iter() {
4370                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4371                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4372                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4373         }
4374
4375         send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4376 }
4377
4378 #[test]
4379 fn test_manager_serialize_deserialize_events() {
4380         // This test makes sure the events field in ChannelManager survives de/serialization
4381         let chanmon_cfgs = create_chanmon_cfgs(2);
4382         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4383         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4384         let fee_estimator: test_utils::TestFeeEstimator;
4385         let persister: test_utils::TestPersister;
4386         let logger: test_utils::TestLogger;
4387         let new_chain_monitor: test_utils::TestChainMonitor;
4388         let keys_manager: test_utils::TestKeysInterface;
4389         let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4390         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4391
4392         // Start creating a channel, but stop right before broadcasting the event message FundingBroadcastSafe
4393         let channel_value = 100000;
4394         let push_msat = 10001;
4395         let a_flags = InitFeatures::known();
4396         let b_flags = InitFeatures::known();
4397         let node_a = nodes.pop().unwrap();
4398         let node_b = nodes.pop().unwrap();
4399         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4400         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()));
4401         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()));
4402
4403         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4404
4405         node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
4406         check_added_monitors!(node_a, 0);
4407
4408         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()));
4409         {
4410                 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4411                 assert_eq!(added_monitors.len(), 1);
4412                 assert_eq!(added_monitors[0].0, funding_output);
4413                 added_monitors.clear();
4414         }
4415
4416         node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id()));
4417         {
4418                 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4419                 assert_eq!(added_monitors.len(), 1);
4420                 assert_eq!(added_monitors[0].0, funding_output);
4421                 added_monitors.clear();
4422         }
4423         // Normally, this is where node_a would check for a FundingBroadcastSafe event, but the test de/serializes first instead
4424
4425         nodes.push(node_a);
4426         nodes.push(node_b);
4427
4428         // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4429         let nodes_0_serialized = nodes[0].node.encode();
4430         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4431         nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
4432
4433         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4434         logger = test_utils::TestLogger::new();
4435         persister = test_utils::TestPersister{};
4436         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister);
4437         nodes[0].chain_monitor = &new_chain_monitor;
4438         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4439         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read).unwrap();
4440         assert!(chan_0_monitor_read.is_empty());
4441
4442         let mut nodes_0_read = &nodes_0_serialized[..];
4443         let config = UserConfig::default();
4444         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4445         let (_, nodes_0_deserialized_tmp) = {
4446                 let mut channel_monitors = HashMap::new();
4447                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4448                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4449                         default_config: config,
4450                         keys_manager: &keys_manager,
4451                         fee_estimator: &fee_estimator,
4452                         chain_monitor: nodes[0].chain_monitor,
4453                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4454                         logger: &logger,
4455                         channel_monitors,
4456                 }).unwrap()
4457         };
4458         nodes_0_deserialized = nodes_0_deserialized_tmp;
4459         assert!(nodes_0_read.is_empty());
4460
4461         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4462
4463         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4464         nodes[0].node = &nodes_0_deserialized;
4465
4466         // After deserializing, make sure the FundingBroadcastSafe event is still held by the channel manager
4467         let events_4 = nodes[0].node.get_and_clear_pending_events();
4468         assert_eq!(events_4.len(), 1);
4469         match events_4[0] {
4470                 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
4471                         assert_eq!(user_channel_id, 42);
4472                         assert_eq!(*funding_txo, funding_output);
4473                 },
4474                 _ => panic!("Unexpected event"),
4475         };
4476
4477         // Make sure the channel is functioning as though the de/serialization never happened
4478         assert_eq!(nodes[0].node.list_channels().len(), 1);
4479         check_added_monitors!(nodes[0], 1);
4480
4481         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4482         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4483         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4484         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4485
4486         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4487         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4488         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4489         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4490
4491         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4492         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4493         for node in nodes.iter() {
4494                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4495                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4496                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4497         }
4498
4499         send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4500 }
4501
4502 #[test]
4503 fn test_simple_manager_serialize_deserialize() {
4504         let chanmon_cfgs = create_chanmon_cfgs(2);
4505         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4506         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4507         let logger: test_utils::TestLogger;
4508         let fee_estimator: test_utils::TestFeeEstimator;
4509         let persister: test_utils::TestPersister;
4510         let new_chain_monitor: test_utils::TestChainMonitor;
4511         let keys_manager: test_utils::TestKeysInterface;
4512         let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4513         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4514         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4515
4516         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4517         let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4518
4519         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4520
4521         let nodes_0_serialized = nodes[0].node.encode();
4522         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4523         nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
4524
4525         logger = test_utils::TestLogger::new();
4526         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4527         persister = test_utils::TestPersister{};
4528         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister);
4529         nodes[0].chain_monitor = &new_chain_monitor;
4530         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4531         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read).unwrap();
4532         assert!(chan_0_monitor_read.is_empty());
4533
4534         let mut nodes_0_read = &nodes_0_serialized[..];
4535         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4536         let (_, nodes_0_deserialized_tmp) = {
4537                 let mut channel_monitors = HashMap::new();
4538                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4539                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4540                         default_config: UserConfig::default(),
4541                         keys_manager: &keys_manager,
4542                         fee_estimator: &fee_estimator,
4543                         chain_monitor: nodes[0].chain_monitor,
4544                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4545                         logger: &logger,
4546                         channel_monitors,
4547                 }).unwrap()
4548         };
4549         nodes_0_deserialized = nodes_0_deserialized_tmp;
4550         assert!(nodes_0_read.is_empty());
4551
4552         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4553         nodes[0].node = &nodes_0_deserialized;
4554         check_added_monitors!(nodes[0], 1);
4555
4556         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4557
4558         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4559         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage, 1_000_000);
4560 }
4561
4562 #[test]
4563 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4564         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4565         let chanmon_cfgs = create_chanmon_cfgs(4);
4566         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4567         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4568         let logger: test_utils::TestLogger;
4569         let fee_estimator: test_utils::TestFeeEstimator;
4570         let persister: test_utils::TestPersister;
4571         let new_chain_monitor: test_utils::TestChainMonitor;
4572         let keys_manager: test_utils::TestKeysInterface;
4573         let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4574         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4575         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4576         create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known());
4577         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4578
4579         let mut node_0_stale_monitors_serialized = Vec::new();
4580         for monitor in nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter() {
4581                 let mut writer = test_utils::TestVecWriter(Vec::new());
4582                 monitor.1.write_for_disk(&mut writer).unwrap();
4583                 node_0_stale_monitors_serialized.push(writer.0);
4584         }
4585
4586         let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4587
4588         // Serialize the ChannelManager here, but the monitor we keep up-to-date
4589         let nodes_0_serialized = nodes[0].node.encode();
4590
4591         route_payment(&nodes[0], &[&nodes[3]], 1000000);
4592         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4593         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4594         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4595
4596         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4597         // nodes[3])
4598         let mut node_0_monitors_serialized = Vec::new();
4599         for monitor in nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter() {
4600                 let mut writer = test_utils::TestVecWriter(Vec::new());
4601                 monitor.1.write_for_disk(&mut writer).unwrap();
4602                 node_0_monitors_serialized.push(writer.0);
4603         }
4604
4605         logger = test_utils::TestLogger::new();
4606         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4607         persister = test_utils::TestPersister{};
4608         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister);
4609         nodes[0].chain_monitor = &new_chain_monitor;
4610
4611         let mut node_0_stale_monitors = Vec::new();
4612         for serialized in node_0_stale_monitors_serialized.iter() {
4613                 let mut read = &serialized[..];
4614                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read).unwrap();
4615                 assert!(read.is_empty());
4616                 node_0_stale_monitors.push(monitor);
4617         }
4618
4619         let mut node_0_monitors = Vec::new();
4620         for serialized in node_0_monitors_serialized.iter() {
4621                 let mut read = &serialized[..];
4622                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read).unwrap();
4623                 assert!(read.is_empty());
4624                 node_0_monitors.push(monitor);
4625         }
4626
4627         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4628
4629         let mut nodes_0_read = &nodes_0_serialized[..];
4630         if let Err(msgs::DecodeError::InvalidValue) =
4631                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4632                 default_config: UserConfig::default(),
4633                 keys_manager: &keys_manager,
4634                 fee_estimator: &fee_estimator,
4635                 chain_monitor: nodes[0].chain_monitor,
4636                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4637                 logger: &logger,
4638                 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4639         }) { } else {
4640                 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4641         };
4642
4643         let mut nodes_0_read = &nodes_0_serialized[..];
4644         let (_, nodes_0_deserialized_tmp) =
4645                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4646                 default_config: UserConfig::default(),
4647                 keys_manager: &keys_manager,
4648                 fee_estimator: &fee_estimator,
4649                 chain_monitor: nodes[0].chain_monitor,
4650                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4651                 logger: &logger,
4652                 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4653         }).unwrap();
4654         nodes_0_deserialized = nodes_0_deserialized_tmp;
4655         assert!(nodes_0_read.is_empty());
4656
4657         { // Channel close should result in a commitment tx and an HTLC tx
4658                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4659                 assert_eq!(txn.len(), 2);
4660                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4661                 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
4662         }
4663
4664         for monitor in node_0_monitors.drain(..) {
4665                 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4666                 check_added_monitors!(nodes[0], 1);
4667         }
4668         nodes[0].node = &nodes_0_deserialized;
4669
4670         // nodes[1] and nodes[2] have no lost state with nodes[0]...
4671         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4672         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4673         //... and we can even still claim the payment!
4674         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage, 1_000_000);
4675
4676         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4677         let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4678         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4679         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4680         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4681         assert_eq!(msg_events.len(), 1);
4682         if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4683                 match action {
4684                         &ErrorAction::SendErrorMessage { ref msg } => {
4685                                 assert_eq!(msg.channel_id, channel_id);
4686                         },
4687                         _ => panic!("Unexpected event!"),
4688                 }
4689         }
4690 }
4691
4692 macro_rules! check_spendable_outputs {
4693         ($node: expr, $der_idx: expr, $keysinterface: expr, $chan_value: expr) => {
4694                 {
4695                         let events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4696                         let mut txn = Vec::new();
4697                         for event in events {
4698                                 match event {
4699                                         Event::SpendableOutputs { ref outputs } => {
4700                                                 for outp in outputs {
4701                                                         match *outp {
4702                                                                 SpendableOutputDescriptor::StaticOutputCounterpartyPayment { ref outpoint, ref output, ref key_derivation_params } => {
4703                                                                         let input = TxIn {
4704                                                                                 previous_output: outpoint.into_bitcoin_outpoint(),
4705                                                                                 script_sig: Script::new(),
4706                                                                                 sequence: 0,
4707                                                                                 witness: Vec::new(),
4708                                                                         };
4709                                                                         let outp = TxOut {
4710                                                                                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4711                                                                                 value: output.value,
4712                                                                         };
4713                                                                         let mut spend_tx = Transaction {
4714                                                                                 version: 2,
4715                                                                                 lock_time: 0,
4716                                                                                 input: vec![input],
4717                                                                                 output: vec![outp],
4718                                                                         };
4719                                                                         spend_tx.output[0].value -= (spend_tx.get_weight() + 2 + 1 + 73 + 35 + 3) as u64 / 4; // (Max weight + 3 (to round up)) / 4
4720                                                                         let secp_ctx = Secp256k1::new();
4721                                                                         let keys = $keysinterface.derive_channel_keys($chan_value, key_derivation_params.0, key_derivation_params.1);
4722                                                                         let remotepubkey = keys.pubkeys().payment_point;
4723                                                                         let witness_script = Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: remotepubkey}, Network::Testnet).script_pubkey();
4724                                                                         let sighash = Message::from_slice(&bip143::SigHashCache::new(&spend_tx).signature_hash(0, &witness_script, output.value, SigHashType::All)[..]).unwrap();
4725                                                                         let remotesig = secp_ctx.sign(&sighash, &keys.inner.payment_key);
4726                                                                         spend_tx.input[0].witness.push(remotesig.serialize_der().to_vec());
4727                                                                         spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4728                                                                         spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
4729                                                                         txn.push(spend_tx);
4730                                                                 },
4731                                                                 SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref per_commitment_point, ref to_self_delay, ref output, ref key_derivation_params, ref revocation_pubkey } => {
4732                                                                         let input = TxIn {
4733                                                                                 previous_output: outpoint.into_bitcoin_outpoint(),
4734                                                                                 script_sig: Script::new(),
4735                                                                                 sequence: *to_self_delay as u32,
4736                                                                                 witness: Vec::new(),
4737                                                                         };
4738                                                                         let outp = TxOut {
4739                                                                                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4740                                                                                 value: output.value,
4741                                                                         };
4742                                                                         let mut spend_tx = Transaction {
4743                                                                                 version: 2,
4744                                                                                 lock_time: 0,
4745                                                                                 input: vec![input],
4746                                                                                 output: vec![outp],
4747                                                                         };
4748                                                                         let secp_ctx = Secp256k1::new();
4749                                                                         let keys = $keysinterface.derive_channel_keys($chan_value, key_derivation_params.0, key_derivation_params.1);
4750                                                                         if let Ok(delayed_payment_key) = chan_utils::derive_private_key(&secp_ctx, &per_commitment_point, &keys.inner.delayed_payment_base_key) {
4751
4752                                                                                 let delayed_payment_pubkey = PublicKey::from_secret_key(&secp_ctx, &delayed_payment_key);
4753                                                                                 let witness_script = chan_utils::get_revokeable_redeemscript(revocation_pubkey, *to_self_delay, &delayed_payment_pubkey);
4754                                                                                 spend_tx.output[0].value -= (spend_tx.get_weight() + 2 + 1 + 73 + 1 + witness_script.len() + 1 + 3) as u64 / 4; // (Max weight + 3 (to round up)) / 4
4755                                                                                 let sighash = Message::from_slice(&bip143::SigHashCache::new(&spend_tx).signature_hash(0, &witness_script, output.value, SigHashType::All)[..]).unwrap();
4756                                                                                 let local_delayedsig = secp_ctx.sign(&sighash, &delayed_payment_key);
4757                                                                                 spend_tx.input[0].witness.push(local_delayedsig.serialize_der().to_vec());
4758                                                                                 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4759                                                                                 spend_tx.input[0].witness.push(vec!()); //MINIMALIF
4760                                                                                 spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
4761                                                                         } else { panic!() }
4762                                                                         txn.push(spend_tx);
4763                                                                 },
4764                                                                 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
4765                                                                         let secp_ctx = Secp256k1::new();
4766                                                                         let input = TxIn {
4767                                                                                 previous_output: outpoint.into_bitcoin_outpoint(),
4768                                                                                 script_sig: Script::new(),
4769                                                                                 sequence: 0,
4770                                                                                 witness: Vec::new(),
4771                                                                         };
4772                                                                         let outp = TxOut {
4773                                                                                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4774                                                                                 value: output.value,
4775                                                                         };
4776                                                                         let mut spend_tx = Transaction {
4777                                                                                 version: 2,
4778                                                                                 lock_time: 0,
4779                                                                                 input: vec![input],
4780                                                                                 output: vec![outp.clone()],
4781                                                                         };
4782                                                                         spend_tx.output[0].value -= (spend_tx.get_weight() + 2 + 1 + 73 + 35 + 3) as u64 / 4; // (Max weight + 3 (to round up)) / 4
4783                                                                         let secret = {
4784                                                                                 match ExtendedPrivKey::new_master(Network::Testnet, &$node.node_seed) {
4785                                                                                         Ok(master_key) => {
4786                                                                                                 match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx).expect("key space exhausted")) {
4787                                                                                                         Ok(key) => key,
4788                                                                                                         Err(_) => panic!("Your RNG is busted"),
4789                                                                                                 }
4790                                                                                         }
4791                                                                                         Err(_) => panic!("Your rng is busted"),
4792                                                                                 }
4793                                                                         };
4794                                                                         let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
4795                                                                         let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
4796                                                                         let sighash = Message::from_slice(&bip143::SigHashCache::new(&spend_tx).signature_hash(0, &witness_script, output.value, SigHashType::All)[..]).unwrap();
4797                                                                         let sig = secp_ctx.sign(&sighash, &secret.private_key.key);
4798                                                                         spend_tx.input[0].witness.push(sig.serialize_der().to_vec());
4799                                                                         spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4800                                                                         spend_tx.input[0].witness.push(pubkey.key.serialize().to_vec());
4801                                                                         txn.push(spend_tx);
4802                                                                 },
4803                                                         }
4804                                                 }
4805                                         },
4806                                         _ => panic!("Unexpected event"),
4807                                 };
4808                         }
4809                         txn
4810                 }
4811         }
4812 }
4813
4814 #[test]
4815 fn test_claim_sizeable_push_msat() {
4816         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4817         let chanmon_cfgs = create_chanmon_cfgs(2);
4818         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4819         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4820         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4821
4822         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4823         nodes[1].node.force_close_channel(&chan.2);
4824         check_closed_broadcast!(nodes[1], false);
4825         check_added_monitors!(nodes[1], 1);
4826         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4827         assert_eq!(node_txn.len(), 1);
4828         check_spends!(node_txn[0], chan.3);
4829         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
4830
4831         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4832         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4833         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4834
4835         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4836         assert_eq!(spend_txn.len(), 1);
4837         check_spends!(spend_txn[0], node_txn[0]);
4838 }
4839
4840 #[test]
4841 fn test_claim_on_remote_sizeable_push_msat() {
4842         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4843         // to_remote output is encumbered by a P2WPKH
4844         let chanmon_cfgs = create_chanmon_cfgs(2);
4845         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4846         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4847         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4848
4849         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4850         nodes[0].node.force_close_channel(&chan.2);
4851         check_closed_broadcast!(nodes[0], false);
4852         check_added_monitors!(nodes[0], 1);
4853
4854         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4855         assert_eq!(node_txn.len(), 1);
4856         check_spends!(node_txn[0], chan.3);
4857         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
4858
4859         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4860         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4861         check_closed_broadcast!(nodes[1], false);
4862         check_added_monitors!(nodes[1], 1);
4863         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4864
4865         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4866         assert_eq!(spend_txn.len(), 1);
4867         check_spends!(spend_txn[0], node_txn[0]);
4868 }
4869
4870 #[test]
4871 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4872         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4873         // to_remote output is encumbered by a P2WPKH
4874
4875         let chanmon_cfgs = create_chanmon_cfgs(2);
4876         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4877         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4878         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4879
4880         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4881         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4882         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4883         assert_eq!(revoked_local_txn[0].input.len(), 1);
4884         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4885
4886         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4887         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4888         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
4889         check_closed_broadcast!(nodes[1], false);
4890         check_added_monitors!(nodes[1], 1);
4891
4892         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4893         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4894         connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4895         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4896
4897         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4898         assert_eq!(spend_txn.len(), 2);
4899         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4900         check_spends!(spend_txn[1], node_txn[0]);
4901 }
4902
4903 #[test]
4904 fn test_static_spendable_outputs_preimage_tx() {
4905         let chanmon_cfgs = create_chanmon_cfgs(2);
4906         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4907         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4908         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4909
4910         // Create some initial channels
4911         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4912
4913         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4914
4915         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4916         assert_eq!(commitment_tx[0].input.len(), 1);
4917         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4918
4919         // Settle A's commitment tx on B's chain
4920         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4921         assert!(nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000));
4922         check_added_monitors!(nodes[1], 1);
4923         connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
4924         check_added_monitors!(nodes[1], 1);
4925         let events = nodes[1].node.get_and_clear_pending_msg_events();
4926         match events[0] {
4927                 MessageSendEvent::UpdateHTLCs { .. } => {},
4928                 _ => panic!("Unexpected event"),
4929         }
4930         match events[1] {
4931                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4932                 _ => panic!("Unexepected event"),
4933         }
4934
4935         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4936         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4937         assert_eq!(node_txn.len(), 3);
4938         check_spends!(node_txn[0], commitment_tx[0]);
4939         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4940         check_spends!(node_txn[1], chan_1.3);
4941         check_spends!(node_txn[2], node_txn[1]);
4942
4943         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4944         connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4945         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4946
4947         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4948         assert_eq!(spend_txn.len(), 1);
4949         check_spends!(spend_txn[0], node_txn[0]);
4950 }
4951
4952 #[test]
4953 fn test_static_spendable_outputs_timeout_tx() {
4954         let chanmon_cfgs = create_chanmon_cfgs(2);
4955         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4956         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4957         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4958
4959         // Create some initial channels
4960         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4961
4962         // Rebalance the network a bit by relaying one payment through all the channels ...
4963         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
4964
4965         let (_, our_payment_hash) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4966
4967         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4968         assert_eq!(commitment_tx[0].input.len(), 1);
4969         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4970
4971         // Settle A's commitment tx on B' chain
4972         let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
4973         connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()] }, 0);
4974         check_added_monitors!(nodes[1], 1);
4975         let events = nodes[1].node.get_and_clear_pending_msg_events();
4976         match events[0] {
4977                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4978                 _ => panic!("Unexpected event"),
4979         }
4980
4981         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4982         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4983         assert_eq!(node_txn.len(), 3); // ChannelManager : 2 (local commitent tx + HTLC-timeout), ChannelMonitor: timeout tx
4984         check_spends!(node_txn[0],  commitment_tx[0].clone());
4985         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4986         check_spends!(node_txn[1], chan_1.3.clone());
4987         check_spends!(node_txn[2], node_txn[1]);
4988
4989         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4990         connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4991         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4992         expect_payment_failed!(nodes[1], our_payment_hash, true);
4993
4994         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4995         assert_eq!(spend_txn.len(), 2); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4996         check_spends!(spend_txn[1], node_txn[0]);
4997 }
4998
4999 #[test]
5000 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
5001         let chanmon_cfgs = create_chanmon_cfgs(2);
5002         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5003         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5004         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5005
5006         // Create some initial channels
5007         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5008
5009         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5010         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5011         assert_eq!(revoked_local_txn[0].input.len(), 1);
5012         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5013
5014         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
5015
5016         let  header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5017         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
5018         check_closed_broadcast!(nodes[1], false);
5019         check_added_monitors!(nodes[1], 1);
5020
5021         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5022         assert_eq!(node_txn.len(), 2);
5023         assert_eq!(node_txn[0].input.len(), 2);
5024         check_spends!(node_txn[0], revoked_local_txn[0]);
5025
5026         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5027         connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
5028         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5029
5030         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5031         assert_eq!(spend_txn.len(), 1);
5032         check_spends!(spend_txn[0], node_txn[0]);
5033 }
5034
5035 #[test]
5036 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
5037         let chanmon_cfgs = create_chanmon_cfgs(2);
5038         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5039         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5040         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5041
5042         // Create some initial channels
5043         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5044
5045         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5046         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5047         assert_eq!(revoked_local_txn[0].input.len(), 1);
5048         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5049
5050         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
5051
5052         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5053         // A will generate HTLC-Timeout from revoked commitment tx
5054         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5055         check_closed_broadcast!(nodes[0], false);
5056         check_added_monitors!(nodes[0], 1);
5057
5058         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5059         assert_eq!(revoked_htlc_txn.len(), 2);
5060         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5061         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5062         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5063         check_spends!(revoked_htlc_txn[1], chan_1.3);
5064
5065         // B will generate justice tx from A's revoked commitment/HTLC tx
5066         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 0);
5067         check_closed_broadcast!(nodes[1], false);
5068         check_added_monitors!(nodes[1], 1);
5069
5070         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5071         assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
5072         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5073         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5074         // transactions next...
5075         assert_eq!(node_txn[0].input.len(), 3);
5076         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5077
5078         assert_eq!(node_txn[1].input.len(), 2);
5079         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
5080         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5081                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5082         } else {
5083                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5084                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5085         }
5086
5087         assert_eq!(node_txn[2].input.len(), 1);
5088         check_spends!(node_txn[2], chan_1.3);
5089
5090         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5091         connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[1].clone()] }, 1);
5092         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5093
5094         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
5095         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5096         assert_eq!(spend_txn.len(), 1);
5097         assert_eq!(spend_txn[0].input.len(), 1);
5098         check_spends!(spend_txn[0], node_txn[1]);
5099 }
5100
5101 #[test]
5102 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
5103         let chanmon_cfgs = create_chanmon_cfgs(2);
5104         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5105         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5106         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5107
5108         // Create some initial channels
5109         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5110
5111         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5112         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5113         assert_eq!(revoked_local_txn[0].input.len(), 1);
5114         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5115
5116         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
5117         assert_eq!(revoked_local_txn[0].output.len(), 2);
5118
5119         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
5120
5121         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5122         // B will generate HTLC-Success from revoked commitment tx
5123         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5124         check_closed_broadcast!(nodes[1], false);
5125         check_added_monitors!(nodes[1], 1);
5126         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5127
5128         assert_eq!(revoked_htlc_txn.len(), 2);
5129         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5130         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5131         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5132
5133         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5134         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5135         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5136
5137         // A will generate justice tx from B's revoked commitment/HTLC tx
5138         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
5139         check_closed_broadcast!(nodes[0], false);
5140         check_added_monitors!(nodes[0], 1);
5141
5142         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5143         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5144
5145         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5146         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5147         // transactions next...
5148         assert_eq!(node_txn[0].input.len(), 2);
5149         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5150         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5151                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5152         } else {
5153                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5154                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5155         }
5156
5157         assert_eq!(node_txn[1].input.len(), 1);
5158         check_spends!(node_txn[1], revoked_htlc_txn[0]);
5159
5160         check_spends!(node_txn[2], chan_1.3);
5161
5162         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5163         connect_block(&nodes[0], &Block { header: header_1, txdata: vec![node_txn[1].clone()] }, 1);
5164         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5165
5166         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5167         // didn't try to generate any new transactions.
5168
5169         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5170         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5171         assert_eq!(spend_txn.len(), 2);
5172         assert_eq!(spend_txn[0].input.len(), 1);
5173         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5174         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5175         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5176 }
5177
5178 #[test]
5179 fn test_onchain_to_onchain_claim() {
5180         // Test that in case of channel closure, we detect the state of output and claim HTLC
5181         // on downstream peer's remote commitment tx.
5182         // First, have C claim an HTLC against its own latest commitment transaction.
5183         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5184         // channel.
5185         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5186         // gets broadcast.
5187
5188         let chanmon_cfgs = create_chanmon_cfgs(3);
5189         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5190         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5191         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5192
5193         // Create some initial channels
5194         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5195         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5196
5197         // Rebalance the network a bit by relaying one payment through all the channels ...
5198         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5199         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5200
5201         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5202         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5203         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5204         check_spends!(commitment_tx[0], chan_2.3);
5205         nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000);
5206         check_added_monitors!(nodes[2], 1);
5207         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5208         assert!(updates.update_add_htlcs.is_empty());
5209         assert!(updates.update_fail_htlcs.is_empty());
5210         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5211         assert!(updates.update_fail_malformed_htlcs.is_empty());
5212
5213         connect_block(&nodes[2], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
5214         check_closed_broadcast!(nodes[2], false);
5215         check_added_monitors!(nodes[2], 1);
5216
5217         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5218         assert_eq!(c_txn.len(), 3);
5219         assert_eq!(c_txn[0], c_txn[2]);
5220         assert_eq!(commitment_tx[0], c_txn[1]);
5221         check_spends!(c_txn[1], chan_2.3);
5222         check_spends!(c_txn[2], c_txn[1]);
5223         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5224         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5225         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5226         assert_eq!(c_txn[0].lock_time, 0); // Success tx
5227
5228         // 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
5229         connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
5230         {
5231                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5232                 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-timeout tx
5233                 assert_eq!(b_txn.len(), 3);
5234                 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
5235                 check_spends!(b_txn[2], b_txn[1]); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
5236                 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5237                 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5238                 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5239                 check_spends!(b_txn[0], c_txn[1]); // timeout tx on C remote commitment tx, issued by ChannelMonitor
5240                 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5241                 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5242                 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5243                 b_txn.clear();
5244         }
5245         check_added_monitors!(nodes[1], 1);
5246         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5247         check_added_monitors!(nodes[1], 1);
5248         match msg_events[0] {
5249                 MessageSendEvent::BroadcastChannelUpdate {  .. } => {},
5250                 _ => panic!("Unexpected event"),
5251         }
5252         match msg_events[1] {
5253                 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, .. } } => {
5254                         assert!(update_add_htlcs.is_empty());
5255                         assert!(update_fail_htlcs.is_empty());
5256                         assert_eq!(update_fulfill_htlcs.len(), 1);
5257                         assert!(update_fail_malformed_htlcs.is_empty());
5258                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5259                 },
5260                 _ => panic!("Unexpected event"),
5261         };
5262         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5263         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5264         connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
5265         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5266         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5267         assert_eq!(b_txn.len(), 3);
5268         check_spends!(b_txn[1], chan_1.3);
5269         check_spends!(b_txn[2], b_txn[1]);
5270         check_spends!(b_txn[0], commitment_tx[0]);
5271         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5272         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5273         assert_eq!(b_txn[0].lock_time, 0); // Success tx
5274
5275         check_closed_broadcast!(nodes[1], false);
5276         check_added_monitors!(nodes[1], 1);
5277 }
5278
5279 #[test]
5280 fn test_duplicate_payment_hash_one_failure_one_success() {
5281         // Topology : A --> B --> C
5282         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5283         let chanmon_cfgs = create_chanmon_cfgs(3);
5284         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5285         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5286         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5287
5288         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5289         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5290
5291         let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5292         *nodes[0].network_payment_count.borrow_mut() -= 1;
5293         assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
5294
5295         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5296         assert_eq!(commitment_txn[0].input.len(), 1);
5297         check_spends!(commitment_txn[0], chan_2.3);
5298
5299         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5300         connect_block(&nodes[1], &Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
5301         check_closed_broadcast!(nodes[1], false);
5302         check_added_monitors!(nodes[1], 1);
5303
5304         let htlc_timeout_tx;
5305         { // Extract one of the two HTLC-Timeout transaction
5306                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5307                 // ChannelMonitor: timeout tx * 2, ChannelManager: local commitment tx + HTLC-timeout * 2
5308                 assert_eq!(node_txn.len(), 5);
5309                 check_spends!(node_txn[0], commitment_txn[0]);
5310                 assert_eq!(node_txn[0].input.len(), 1);
5311                 check_spends!(node_txn[1], commitment_txn[0]);
5312                 assert_eq!(node_txn[1].input.len(), 1);
5313                 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
5314                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5315                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5316                 check_spends!(node_txn[2], chan_2.3);
5317                 check_spends!(node_txn[3], node_txn[2]);
5318                 check_spends!(node_txn[4], node_txn[2]);
5319                 htlc_timeout_tx = node_txn[1].clone();
5320         }
5321
5322         nodes[2].node.claim_funds(our_payment_preimage, &None, 900_000);
5323         connect_block(&nodes[2], &Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
5324         check_added_monitors!(nodes[2], 3);
5325         let events = nodes[2].node.get_and_clear_pending_msg_events();
5326         match events[0] {
5327                 MessageSendEvent::UpdateHTLCs { .. } => {},
5328                 _ => panic!("Unexpected event"),
5329         }
5330         match events[1] {
5331                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5332                 _ => panic!("Unexepected event"),
5333         }
5334         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5335         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)
5336         check_spends!(htlc_success_txn[2], chan_2.3);
5337         check_spends!(htlc_success_txn[3], htlc_success_txn[2]);
5338         check_spends!(htlc_success_txn[4], htlc_success_txn[2]);
5339         assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
5340         assert_eq!(htlc_success_txn[0].input.len(), 1);
5341         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5342         assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
5343         assert_eq!(htlc_success_txn[1].input.len(), 1);
5344         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5345         assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
5346         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5347         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5348
5349         connect_block(&nodes[1], &Block { header, txdata: vec![htlc_timeout_tx] }, 200);
5350         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 200, true, header.block_hash());
5351         expect_pending_htlcs_forwardable!(nodes[1]);
5352         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5353         assert!(htlc_updates.update_add_htlcs.is_empty());
5354         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5355         assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
5356         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5357         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5358         check_added_monitors!(nodes[1], 1);
5359
5360         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5361         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5362         {
5363                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5364                 let events = nodes[0].node.get_and_clear_pending_msg_events();
5365                 assert_eq!(events.len(), 1);
5366                 match events[0] {
5367                         MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. }  } => {
5368                         },
5369                         _ => { panic!("Unexpected event"); }
5370                 }
5371         }
5372         expect_payment_failed!(nodes[0], duplicate_payment_hash, false);
5373
5374         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5375         connect_block(&nodes[1], &Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
5376         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5377         assert!(updates.update_add_htlcs.is_empty());
5378         assert!(updates.update_fail_htlcs.is_empty());
5379         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5380         assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
5381         assert!(updates.update_fail_malformed_htlcs.is_empty());
5382         check_added_monitors!(nodes[1], 1);
5383
5384         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5385         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5386
5387         let events = nodes[0].node.get_and_clear_pending_events();
5388         match events[0] {
5389                 Event::PaymentSent { ref payment_preimage } => {
5390                         assert_eq!(*payment_preimage, our_payment_preimage);
5391                 }
5392                 _ => panic!("Unexpected event"),
5393         }
5394 }
5395
5396 #[test]
5397 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5398         let chanmon_cfgs = create_chanmon_cfgs(2);
5399         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5400         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5401         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5402
5403         // Create some initial channels
5404         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5405
5406         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5407         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5408         assert_eq!(local_txn[0].input.len(), 1);
5409         check_spends!(local_txn[0], chan_1.3);
5410
5411         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5412         nodes[1].node.claim_funds(payment_preimage, &None, 9_000_000);
5413         check_added_monitors!(nodes[1], 1);
5414         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5415         connect_block(&nodes[1], &Block { header, txdata: vec![local_txn[0].clone()] }, 1);
5416         check_added_monitors!(nodes[1], 1);
5417         let events = nodes[1].node.get_and_clear_pending_msg_events();
5418         match events[0] {
5419                 MessageSendEvent::UpdateHTLCs { .. } => {},
5420                 _ => panic!("Unexpected event"),
5421         }
5422         match events[1] {
5423                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5424                 _ => panic!("Unexepected event"),
5425         }
5426         let node_txn = {
5427                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5428                 assert_eq!(node_txn[0].input.len(), 1);
5429                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5430                 check_spends!(node_txn[0], local_txn[0]);
5431                 vec![node_txn[0].clone(), node_txn[2].clone()]
5432         };
5433
5434         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5435         connect_block(&nodes[1], &Block { header: header_201, txdata: node_txn.clone() }, 201);
5436         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5437
5438         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5439         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5440         assert_eq!(spend_txn.len(), 2);
5441         check_spends!(spend_txn[0], node_txn[0]);
5442         check_spends!(spend_txn[1], node_txn[1]);
5443 }
5444
5445 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5446         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5447         // unrevoked commitment transaction.
5448         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5449         // a remote RAA before they could be failed backwards (and combinations thereof).
5450         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5451         // use the same payment hashes.
5452         // Thus, we use a six-node network:
5453         //
5454         // A \         / E
5455         //    - C - D -
5456         // B /         \ F
5457         // And test where C fails back to A/B when D announces its latest commitment transaction
5458         let chanmon_cfgs = create_chanmon_cfgs(6);
5459         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5460         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
5461         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5462         let logger = test_utils::TestLogger::new();
5463
5464         create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5465         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5466         let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5467         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5468         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5469
5470         // Rebalance and check output sanity...
5471         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000, 500_000);
5472         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000, 500_000);
5473         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5474
5475         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5476         // 0th HTLC:
5477         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
5478         // 1st HTLC:
5479         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
5480         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
5481         let our_node_id = &nodes[1].node.get_our_node_id();
5482         let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV, &logger).unwrap();
5483         // 2nd HTLC:
5484         send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], ds_dust_limit*1000, payment_hash_1); // not added < dust limit + HTLC tx fee
5485         // 3rd HTLC:
5486         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], ds_dust_limit*1000, payment_hash_2); // not added < dust limit + HTLC tx fee
5487         // 4th HTLC:
5488         let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5489         // 5th HTLC:
5490         let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5491         let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
5492         // 6th HTLC:
5493         send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
5494         // 7th HTLC:
5495         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
5496
5497         // 8th HTLC:
5498         let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5499         // 9th HTLC:
5500         let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV, &logger).unwrap();
5501         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], ds_dust_limit*1000, payment_hash_5); // not added < dust limit + HTLC tx fee
5502
5503         // 10th HTLC:
5504         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
5505         // 11th HTLC:
5506         let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
5507         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
5508
5509         // Double-check that six of the new HTLC were added
5510         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5511         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5512         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5513         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5514
5515         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5516         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5517         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1, &None));
5518         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3, &None));
5519         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5, &None));
5520         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6, &None));
5521         check_added_monitors!(nodes[4], 0);
5522         expect_pending_htlcs_forwardable!(nodes[4]);
5523         check_added_monitors!(nodes[4], 1);
5524
5525         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5526         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5527         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5528         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5529         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5530         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5531
5532         // Fail 3rd below-dust and 7th above-dust HTLCs
5533         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2, &None));
5534         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4, &None));
5535         check_added_monitors!(nodes[5], 0);
5536         expect_pending_htlcs_forwardable!(nodes[5]);
5537         check_added_monitors!(nodes[5], 1);
5538
5539         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5540         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5541         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5542         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5543
5544         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5545
5546         expect_pending_htlcs_forwardable!(nodes[3]);
5547         check_added_monitors!(nodes[3], 1);
5548         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5549         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5550         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5551         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5552         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5553         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5554         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5555         if deliver_last_raa {
5556                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5557         } else {
5558                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5559         }
5560
5561         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5562         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5563         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5564         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5565         //
5566         // We now broadcast the latest commitment transaction, which *should* result in failures for
5567         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5568         // the non-broadcast above-dust HTLCs.
5569         //
5570         // Alternatively, we may broadcast the previous commitment transaction, which should only
5571         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5572         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5573
5574         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5575         if announce_latest {
5576                 connect_block(&nodes[2], &Block { header, txdata: vec![ds_last_commitment_tx[0].clone()]}, 1);
5577         } else {
5578                 connect_block(&nodes[2], &Block { header, txdata: vec![ds_prev_commitment_tx[0].clone()]}, 1);
5579         }
5580         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1, 1, true,  header.block_hash());
5581         check_closed_broadcast!(nodes[2], false);
5582         expect_pending_htlcs_forwardable!(nodes[2]);
5583         check_added_monitors!(nodes[2], 3);
5584
5585         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5586         assert_eq!(cs_msgs.len(), 2);
5587         let mut a_done = false;
5588         for msg in cs_msgs {
5589                 match msg {
5590                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5591                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5592                                 // should be failed-backwards here.
5593                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5594                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5595                                         for htlc in &updates.update_fail_htlcs {
5596                                                 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 });
5597                                         }
5598                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5599                                         assert!(!a_done);
5600                                         a_done = true;
5601                                         &nodes[0]
5602                                 } else {
5603                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5604                                         for htlc in &updates.update_fail_htlcs {
5605                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5606                                         }
5607                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5608                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5609                                         &nodes[1]
5610                                 };
5611                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5612                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5613                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5614                                 if announce_latest {
5615                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5616                                         if *node_id == nodes[0].node.get_our_node_id() {
5617                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5618                                         }
5619                                 }
5620                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5621                         },
5622                         _ => panic!("Unexpected event"),
5623                 }
5624         }
5625
5626         let as_events = nodes[0].node.get_and_clear_pending_events();
5627         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5628         let mut as_failds = HashSet::new();
5629         for event in as_events.iter() {
5630                 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5631                         assert!(as_failds.insert(*payment_hash));
5632                         if *payment_hash != payment_hash_2 {
5633                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5634                         } else {
5635                                 assert!(!rejected_by_dest);
5636                         }
5637                 } else { panic!("Unexpected event"); }
5638         }
5639         assert!(as_failds.contains(&payment_hash_1));
5640         assert!(as_failds.contains(&payment_hash_2));
5641         if announce_latest {
5642                 assert!(as_failds.contains(&payment_hash_3));
5643                 assert!(as_failds.contains(&payment_hash_5));
5644         }
5645         assert!(as_failds.contains(&payment_hash_6));
5646
5647         let bs_events = nodes[1].node.get_and_clear_pending_events();
5648         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5649         let mut bs_failds = HashSet::new();
5650         for event in bs_events.iter() {
5651                 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5652                         assert!(bs_failds.insert(*payment_hash));
5653                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5654                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5655                         } else {
5656                                 assert!(!rejected_by_dest);
5657                         }
5658                 } else { panic!("Unexpected event"); }
5659         }
5660         assert!(bs_failds.contains(&payment_hash_1));
5661         assert!(bs_failds.contains(&payment_hash_2));
5662         if announce_latest {
5663                 assert!(bs_failds.contains(&payment_hash_4));
5664         }
5665         assert!(bs_failds.contains(&payment_hash_5));
5666
5667         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5668         // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
5669         // to unknown-preimage-etc, B should have gotten 2. Thus, in the
5670         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
5671         // PaymentFailureNetworkUpdates.
5672         let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
5673         assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5674         let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5675         assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5676         for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
5677                 match event {
5678                         &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
5679                         _ => panic!("Unexpected event"),
5680                 }
5681         }
5682 }
5683
5684 #[test]
5685 fn test_fail_backwards_latest_remote_announce_a() {
5686         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5687 }
5688
5689 #[test]
5690 fn test_fail_backwards_latest_remote_announce_b() {
5691         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5692 }
5693
5694 #[test]
5695 fn test_fail_backwards_previous_remote_announce() {
5696         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5697         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5698         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5699 }
5700
5701 #[test]
5702 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5703         let chanmon_cfgs = create_chanmon_cfgs(2);
5704         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5705         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5706         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5707
5708         // Create some initial channels
5709         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5710
5711         let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5712         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5713         assert_eq!(local_txn[0].input.len(), 1);
5714         check_spends!(local_txn[0], chan_1.3);
5715
5716         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5717         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5718         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] }, 200);
5719         check_closed_broadcast!(nodes[0], false);
5720         check_added_monitors!(nodes[0], 1);
5721
5722         let htlc_timeout = {
5723                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5724                 assert_eq!(node_txn[0].input.len(), 1);
5725                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5726                 check_spends!(node_txn[0], local_txn[0]);
5727                 node_txn[0].clone()
5728         };
5729
5730         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5731         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
5732         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5733         expect_payment_failed!(nodes[0], our_payment_hash, true);
5734
5735         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5736         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5737         assert_eq!(spend_txn.len(), 2);
5738         check_spends!(spend_txn[0], local_txn[0]);
5739         check_spends!(spend_txn[1], htlc_timeout);
5740 }
5741
5742 #[test]
5743 fn test_key_derivation_params() {
5744         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5745         // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5746         // let us re-derive the channel key set to then derive a delayed_payment_key.
5747
5748         let chanmon_cfgs = create_chanmon_cfgs(3);
5749
5750         // We manually create the node configuration to backup the seed.
5751         let seed = [42; 32];
5752         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5753         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);
5754         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, node_seed: seed };
5755         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5756         node_cfgs.remove(0);
5757         node_cfgs.insert(0, node);
5758
5759         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5760         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5761
5762         // Create some initial channels
5763         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5764         // for node 0
5765         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5766         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5767         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5768
5769         let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5770         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5771         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5772         assert_eq!(local_txn_1[0].input.len(), 1);
5773         check_spends!(local_txn_1[0], chan_1.3);
5774
5775         // We check funding pubkey are unique
5776         let (from_0_funding_key_0, from_0_funding_key_1) = (PublicKey::from_slice(&local_txn_0[0].input[0].witness[3][2..35]), PublicKey::from_slice(&local_txn_0[0].input[0].witness[3][36..69]));
5777         let (from_1_funding_key_0, from_1_funding_key_1) = (PublicKey::from_slice(&local_txn_1[0].input[0].witness[3][2..35]), PublicKey::from_slice(&local_txn_1[0].input[0].witness[3][36..69]));
5778         if from_0_funding_key_0 == from_1_funding_key_0
5779             || from_0_funding_key_0 == from_1_funding_key_1
5780             || from_0_funding_key_1 == from_1_funding_key_0
5781             || from_0_funding_key_1 == from_1_funding_key_1 {
5782                 panic!("Funding pubkeys aren't unique");
5783         }
5784
5785         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5786         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5787         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn_1[0].clone()] }, 200);
5788         check_closed_broadcast!(nodes[0], false);
5789         check_added_monitors!(nodes[0], 1);
5790
5791         let htlc_timeout = {
5792                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5793                 assert_eq!(node_txn[0].input.len(), 1);
5794                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5795                 check_spends!(node_txn[0], local_txn_1[0]);
5796                 node_txn[0].clone()
5797         };
5798
5799         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5800         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
5801         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5802         expect_payment_failed!(nodes[0], our_payment_hash, true);
5803
5804         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5805         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5806         let spend_txn = check_spendable_outputs!(nodes[0], 1, new_keys_manager, 100000);
5807         assert_eq!(spend_txn.len(), 2);
5808         check_spends!(spend_txn[0], local_txn_1[0]);
5809         check_spends!(spend_txn[1], htlc_timeout);
5810 }
5811
5812 #[test]
5813 fn test_static_output_closing_tx() {
5814         let chanmon_cfgs = create_chanmon_cfgs(2);
5815         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5816         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5817         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5818
5819         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5820
5821         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
5822         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5823
5824         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5825         connect_block(&nodes[0], &Block { header, txdata: vec![closing_tx.clone()] }, 0);
5826         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
5827
5828         let spend_txn = check_spendable_outputs!(nodes[0], 2, node_cfgs[0].keys_manager, 100000);
5829         assert_eq!(spend_txn.len(), 1);
5830         check_spends!(spend_txn[0], closing_tx);
5831
5832         connect_block(&nodes[1], &Block { header, txdata: vec![closing_tx.clone()] }, 0);
5833         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
5834
5835         let spend_txn = check_spendable_outputs!(nodes[1], 2, node_cfgs[1].keys_manager, 100000);
5836         assert_eq!(spend_txn.len(), 1);
5837         check_spends!(spend_txn[0], closing_tx);
5838 }
5839
5840 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5841         let chanmon_cfgs = create_chanmon_cfgs(2);
5842         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5843         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5844         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5845         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5846
5847         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5848
5849         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5850         // present in B's local commitment transaction, but none of A's commitment transactions.
5851         assert!(nodes[1].node.claim_funds(our_payment_preimage, &None, if use_dust { 50_000 } else { 3_000_000 }));
5852         check_added_monitors!(nodes[1], 1);
5853
5854         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5855         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5856         let events = nodes[0].node.get_and_clear_pending_events();
5857         assert_eq!(events.len(), 1);
5858         match events[0] {
5859                 Event::PaymentSent { payment_preimage } => {
5860                         assert_eq!(payment_preimage, our_payment_preimage);
5861                 },
5862                 _ => panic!("Unexpected event"),
5863         }
5864
5865         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5866         check_added_monitors!(nodes[0], 1);
5867         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5868         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5869         check_added_monitors!(nodes[1], 1);
5870
5871         let mut block = Block {
5872                 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5873                 txdata: vec![],
5874         };
5875         for i in 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + CHAN_CONFIRM_DEPTH + 1 {
5876                 connect_block(&nodes[1], &block, i);
5877                 block.header.prev_blockhash = block.block_hash();
5878         }
5879         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5880         check_closed_broadcast!(nodes[1], false);
5881         check_added_monitors!(nodes[1], 1);
5882 }
5883
5884 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5885         let chanmon_cfgs = create_chanmon_cfgs(2);
5886         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5887         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5888         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5889         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5890         let logger = test_utils::TestLogger::new();
5891
5892         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5893         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5894         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &Vec::new(), if use_dust { 50000 } else { 3000000 }, TEST_FINAL_CLTV, &logger).unwrap();
5895         nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
5896         check_added_monitors!(nodes[0], 1);
5897
5898         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5899
5900         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5901         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5902         // to "time out" the HTLC.
5903
5904         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5905
5906         for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5907                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()}, i);
5908                 header.prev_blockhash = header.block_hash();
5909         }
5910         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5911         check_closed_broadcast!(nodes[0], false);
5912         check_added_monitors!(nodes[0], 1);
5913 }
5914
5915 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5916         let chanmon_cfgs = create_chanmon_cfgs(3);
5917         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5918         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5919         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5920         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5921
5922         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5923         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5924         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5925         // actually revoked.
5926         let htlc_value = if use_dust { 50000 } else { 3000000 };
5927         let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5928         assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash, &None));
5929         expect_pending_htlcs_forwardable!(nodes[1]);
5930         check_added_monitors!(nodes[1], 1);
5931
5932         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5933         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5934         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5935         check_added_monitors!(nodes[0], 1);
5936         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5937         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5938         check_added_monitors!(nodes[1], 1);
5939         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5940         check_added_monitors!(nodes[1], 1);
5941         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5942
5943         if check_revoke_no_close {
5944                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5945                 check_added_monitors!(nodes[0], 1);
5946         }
5947
5948         let mut block = Block {
5949                 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5950                 txdata: vec![],
5951         };
5952         for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5953                 connect_block(&nodes[0], &block, i);
5954                 block.header.prev_blockhash = block.block_hash();
5955         }
5956         if !check_revoke_no_close {
5957                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5958                 check_closed_broadcast!(nodes[0], false);
5959                 check_added_monitors!(nodes[0], 1);
5960         } else {
5961                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5962         }
5963 }
5964
5965 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5966 // There are only a few cases to test here:
5967 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5968 //    broadcastable commitment transactions result in channel closure,
5969 //  * its included in an unrevoked-but-previous remote commitment transaction,
5970 //  * its included in the latest remote or local commitment transactions.
5971 // We test each of the three possible commitment transactions individually and use both dust and
5972 // non-dust HTLCs.
5973 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5974 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5975 // tested for at least one of the cases in other tests.
5976 #[test]
5977 fn htlc_claim_single_commitment_only_a() {
5978         do_htlc_claim_local_commitment_only(true);
5979         do_htlc_claim_local_commitment_only(false);
5980
5981         do_htlc_claim_current_remote_commitment_only(true);
5982         do_htlc_claim_current_remote_commitment_only(false);
5983 }
5984
5985 #[test]
5986 fn htlc_claim_single_commitment_only_b() {
5987         do_htlc_claim_previous_remote_commitment_only(true, false);
5988         do_htlc_claim_previous_remote_commitment_only(false, false);
5989         do_htlc_claim_previous_remote_commitment_only(true, true);
5990         do_htlc_claim_previous_remote_commitment_only(false, true);
5991 }
5992
5993 #[test]
5994 #[should_panic]
5995 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5996         let chanmon_cfgs = create_chanmon_cfgs(2);
5997         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5998         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5999         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6000         //Force duplicate channel ids
6001         for node in nodes.iter() {
6002                 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
6003         }
6004
6005         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
6006         let channel_value_satoshis=10000;
6007         let push_msat=10001;
6008         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6009         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6010         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6011
6012         //Create a second channel with a channel_id collision
6013         assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6014 }
6015
6016 #[test]
6017 fn bolt2_open_channel_sending_node_checks_part2() {
6018         let chanmon_cfgs = create_chanmon_cfgs(2);
6019         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6020         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6021         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6022
6023         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
6024         let channel_value_satoshis=2^24;
6025         let push_msat=10001;
6026         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6027
6028         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
6029         let channel_value_satoshis=10000;
6030         // Test when push_msat is equal to 1000 * funding_satoshis.
6031         let push_msat=1000*channel_value_satoshis+1;
6032         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6033
6034         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
6035         let channel_value_satoshis=10000;
6036         let push_msat=10001;
6037         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
6038         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6039         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
6040
6041         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
6042         // 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
6043         assert!(node0_to_1_send_open_channel.channel_flags<=1);
6044
6045         // 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.
6046         assert!(BREAKDOWN_TIMEOUT>0);
6047         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
6048
6049         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
6050         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
6051         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
6052
6053         // 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.
6054         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
6055         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
6056         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
6057         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
6058         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6059 }
6060
6061 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6062 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6063 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6064 // is no longer affordable once it's freed.
6065 #[test]
6066 fn test_fail_holding_cell_htlc_upon_free() {
6067         let chanmon_cfgs = create_chanmon_cfgs(2);
6068         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6069         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6070         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6071         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6072         let logger = test_utils::TestLogger::new();
6073
6074         // First nodes[0] generates an update_fee, setting the channel's
6075         // pending_update_fee.
6076         nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 20).unwrap();
6077         check_added_monitors!(nodes[0], 1);
6078
6079         let events = nodes[0].node.get_and_clear_pending_msg_events();
6080         assert_eq!(events.len(), 1);
6081         let (update_msg, commitment_signed) = match events[0] {
6082                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6083                         (update_fee.as_ref(), commitment_signed)
6084                 },
6085                 _ => panic!("Unexpected event"),
6086         };
6087
6088         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6089
6090         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6091         let channel_reserve = chan_stat.channel_reserve_msat;
6092         let feerate = get_feerate!(nodes[0], chan.2);
6093
6094         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6095         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6096         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1);
6097         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6098         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &[], max_can_send, TEST_FINAL_CLTV, &logger).unwrap();
6099
6100         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6101         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6102         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6103         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6104
6105         // Flush the pending fee update.
6106         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6107         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6108         check_added_monitors!(nodes[1], 1);
6109         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6110         check_added_monitors!(nodes[0], 1);
6111
6112         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6113         // HTLC, but now that the fee has been raised the payment will now fail, causing
6114         // us to surface its failure to the user.
6115         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6116         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6117         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 1 HTLC updates".to_string(), 1);
6118         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 ({})", log_bytes!(our_payment_hash.0), chan_stat.channel_reserve_msat);
6119         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6120
6121         // Check that the payment failed to be sent out.
6122         let events = nodes[0].node.get_and_clear_pending_events();
6123         assert_eq!(events.len(), 1);
6124         match &events[0] {
6125                 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6126                         assert_eq!(our_payment_hash.clone(), *payment_hash);
6127                         assert_eq!(*rejected_by_dest, false);
6128                         assert_eq!(*error_code, None);
6129                         assert_eq!(*error_data, None);
6130                 },
6131                 _ => panic!("Unexpected event"),
6132         }
6133 }
6134
6135 // Test that if multiple HTLCs are released from the holding cell and one is
6136 // valid but the other is no longer valid upon release, the valid HTLC can be
6137 // successfully completed while the other one fails as expected.
6138 #[test]
6139 fn test_free_and_fail_holding_cell_htlcs() {
6140         let chanmon_cfgs = create_chanmon_cfgs(2);
6141         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6142         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6143         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6144         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6145         let logger = test_utils::TestLogger::new();
6146
6147         // First nodes[0] generates an update_fee, setting the channel's
6148         // pending_update_fee.
6149         nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 200).unwrap();
6150         check_added_monitors!(nodes[0], 1);
6151
6152         let events = nodes[0].node.get_and_clear_pending_msg_events();
6153         assert_eq!(events.len(), 1);
6154         let (update_msg, commitment_signed) = match events[0] {
6155                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6156                         (update_fee.as_ref(), commitment_signed)
6157                 },
6158                 _ => panic!("Unexpected event"),
6159         };
6160
6161         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6162
6163         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6164         let channel_reserve = chan_stat.channel_reserve_msat;
6165         let feerate = get_feerate!(nodes[0], chan.2);
6166
6167         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6168         let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
6169         let amt_1 = 20000;
6170         let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
6171         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1) - amt_1;
6172         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6173         let route_1 = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &[], amt_1, TEST_FINAL_CLTV, &logger).unwrap();
6174         let route_2 = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &[], amt_2, TEST_FINAL_CLTV, &logger).unwrap();
6175
6176         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6177         nodes[0].node.send_payment(&route_1, payment_hash_1, &None).unwrap();
6178         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6179         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6180         nodes[0].node.send_payment(&route_2, payment_hash_2, &None).unwrap();
6181         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6182         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6183
6184         // Flush the pending fee update.
6185         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6186         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6187         check_added_monitors!(nodes[1], 1);
6188         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6189         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6190         check_added_monitors!(nodes[0], 2);
6191
6192         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6193         // but now that the fee has been raised the second payment will now fail, causing us
6194         // to surface its failure to the user. The first payment should succeed.
6195         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6196         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6197         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 2 HTLC updates".to_string(), 1);
6198         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 ({})", log_bytes!(payment_hash_2.0), chan_stat.channel_reserve_msat);
6199         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6200
6201         // Check that the second payment failed to be sent out.
6202         let events = nodes[0].node.get_and_clear_pending_events();
6203         assert_eq!(events.len(), 1);
6204         match &events[0] {
6205                 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6206                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6207                         assert_eq!(*rejected_by_dest, false);
6208                         assert_eq!(*error_code, None);
6209                         assert_eq!(*error_data, None);
6210                 },
6211                 _ => panic!("Unexpected event"),
6212         }
6213
6214         // Complete the first payment and the RAA from the fee update.
6215         let (payment_event, send_raa_event) = {
6216                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6217                 assert_eq!(msgs.len(), 2);
6218                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6219         };
6220         let raa = match send_raa_event {
6221                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6222                 _ => panic!("Unexpected event"),
6223         };
6224         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6225         check_added_monitors!(nodes[1], 1);
6226         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6227         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6228         let events = nodes[1].node.get_and_clear_pending_events();
6229         assert_eq!(events.len(), 1);
6230         match events[0] {
6231                 Event::PendingHTLCsForwardable { .. } => {},
6232                 _ => panic!("Unexpected event"),
6233         }
6234         nodes[1].node.process_pending_htlc_forwards();
6235         let events = nodes[1].node.get_and_clear_pending_events();
6236         assert_eq!(events.len(), 1);
6237         match events[0] {
6238                 Event::PaymentReceived { .. } => {},
6239                 _ => panic!("Unexpected event"),
6240         }
6241         nodes[1].node.claim_funds(payment_preimage_1, &None, amt_1);
6242         check_added_monitors!(nodes[1], 1);
6243         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6244         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6245         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6246         let events = nodes[0].node.get_and_clear_pending_events();
6247         assert_eq!(events.len(), 1);
6248         match events[0] {
6249                 Event::PaymentSent { ref payment_preimage } => {
6250                         assert_eq!(*payment_preimage, payment_preimage_1);
6251                 }
6252                 _ => panic!("Unexpected event"),
6253         }
6254 }
6255
6256 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6257 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6258 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6259 // once it's freed.
6260 #[test]
6261 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6262         let chanmon_cfgs = create_chanmon_cfgs(3);
6263         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6264         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6265         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6266         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6267         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6268         let logger = test_utils::TestLogger::new();
6269
6270         // First nodes[1] generates an update_fee, setting the channel's
6271         // pending_update_fee.
6272         nodes[1].node.update_fee(chan_1_2.2, get_feerate!(nodes[1], chan_1_2.2) + 20).unwrap();
6273         check_added_monitors!(nodes[1], 1);
6274
6275         let events = nodes[1].node.get_and_clear_pending_msg_events();
6276         assert_eq!(events.len(), 1);
6277         let (update_msg, commitment_signed) = match events[0] {
6278                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6279                         (update_fee.as_ref(), commitment_signed)
6280                 },
6281                 _ => panic!("Unexpected event"),
6282         };
6283
6284         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6285
6286         let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6287         let channel_reserve = chan_stat.channel_reserve_msat;
6288         let feerate = get_feerate!(nodes[0], chan_0_1.2);
6289
6290         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6291         let feemsat = 239;
6292         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6293         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6294         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1) - total_routing_fee_msat;
6295         let payment_event = {
6296                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6297                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, &[], max_can_send, TEST_FINAL_CLTV, &logger).unwrap();
6298                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6299                 check_added_monitors!(nodes[0], 1);
6300
6301                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6302                 assert_eq!(events.len(), 1);
6303
6304                 SendEvent::from_event(events.remove(0))
6305         };
6306         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6307         check_added_monitors!(nodes[1], 0);
6308         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6309         expect_pending_htlcs_forwardable!(nodes[1]);
6310
6311         chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6312         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6313
6314         // Flush the pending fee update.
6315         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6316         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6317         check_added_monitors!(nodes[2], 1);
6318         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6319         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6320         check_added_monitors!(nodes[1], 2);
6321
6322         // A final RAA message is generated to finalize the fee update.
6323         let events = nodes[1].node.get_and_clear_pending_msg_events();
6324         assert_eq!(events.len(), 1);
6325
6326         let raa_msg = match &events[0] {
6327                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6328                         msg.clone()
6329                 },
6330                 _ => panic!("Unexpected event"),
6331         };
6332
6333         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6334         check_added_monitors!(nodes[2], 1);
6335         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6336
6337         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6338         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6339         assert_eq!(process_htlc_forwards_event.len(), 1);
6340         match &process_htlc_forwards_event[0] {
6341                 &Event::PendingHTLCsForwardable { .. } => {},
6342                 _ => panic!("Unexpected event"),
6343         }
6344
6345         // In response, we call ChannelManager's process_pending_htlc_forwards
6346         nodes[1].node.process_pending_htlc_forwards();
6347         check_added_monitors!(nodes[1], 1);
6348
6349         // This causes the HTLC to be failed backwards.
6350         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6351         assert_eq!(fail_event.len(), 1);
6352         let (fail_msg, commitment_signed) = match &fail_event[0] {
6353                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6354                         assert_eq!(updates.update_add_htlcs.len(), 0);
6355                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6356                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6357                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6358                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6359                 },
6360                 _ => panic!("Unexpected event"),
6361         };
6362
6363         // Pass the failure messages back to nodes[0].
6364         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6365         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6366
6367         // Complete the HTLC failure+removal process.
6368         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6369         check_added_monitors!(nodes[0], 1);
6370         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6371         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6372         check_added_monitors!(nodes[1], 2);
6373         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6374         assert_eq!(final_raa_event.len(), 1);
6375         let raa = match &final_raa_event[0] {
6376                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6377                 _ => panic!("Unexpected event"),
6378         };
6379         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6380         let fail_msg_event = nodes[0].node.get_and_clear_pending_msg_events();
6381         assert_eq!(fail_msg_event.len(), 1);
6382         match &fail_msg_event[0] {
6383                 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6384                 _ => panic!("Unexpected event"),
6385         }
6386         let failure_event = nodes[0].node.get_and_clear_pending_events();
6387         assert_eq!(failure_event.len(), 1);
6388         match &failure_event[0] {
6389                 &Event::PaymentFailed { rejected_by_dest, .. } => {
6390                         assert!(!rejected_by_dest);
6391                 },
6392                 _ => panic!("Unexpected event"),
6393         }
6394         check_added_monitors!(nodes[0], 1);
6395 }
6396
6397 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6398 // 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.
6399 //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.
6400
6401 #[test]
6402 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6403         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6404         let chanmon_cfgs = create_chanmon_cfgs(2);
6405         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6406         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6407         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6408         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6409
6410         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6411         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6412         let logger = test_utils::TestLogger::new();
6413         let mut route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6414         route.paths[0][0].fee_msat = 100;
6415
6416         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6417                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6418         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6419         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6420 }
6421
6422 #[test]
6423 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6424         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6425         let chanmon_cfgs = create_chanmon_cfgs(2);
6426         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6427         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6428         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6429         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6430         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6431
6432         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6433         let logger = test_utils::TestLogger::new();
6434         let mut route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6435         route.paths[0][0].fee_msat = 0;
6436         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6437                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6438
6439         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6440         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6441 }
6442
6443 #[test]
6444 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6445         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6446         let chanmon_cfgs = create_chanmon_cfgs(2);
6447         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6448         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6449         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6450         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6451
6452         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6453         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6454         let logger = test_utils::TestLogger::new();
6455         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6456         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6457         check_added_monitors!(nodes[0], 1);
6458         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6459         updates.update_add_htlcs[0].amount_msat = 0;
6460
6461         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6462         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6463         check_closed_broadcast!(nodes[1], true).unwrap();
6464         check_added_monitors!(nodes[1], 1);
6465 }
6466
6467 #[test]
6468 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6469         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6470         //It is enforced when constructing a route.
6471         let chanmon_cfgs = create_chanmon_cfgs(2);
6472         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6473         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6474         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6475         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 0, InitFeatures::known(), InitFeatures::known());
6476         let logger = test_utils::TestLogger::new();
6477
6478         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6479
6480         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6481         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &[], 100000000, 500000001, &logger).unwrap();
6482         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::RouteError { ref err },
6483                 assert_eq!(err, &"Channel CLTV overflowed?"));
6484 }
6485
6486 #[test]
6487 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6488         //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.
6489         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6490         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6491         let chanmon_cfgs = create_chanmon_cfgs(2);
6492         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6493         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6494         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6495         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6496         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6497
6498         let logger = test_utils::TestLogger::new();
6499         for i in 0..max_accepted_htlcs {
6500                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6501                 let payment_event = {
6502                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6503                         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6504                         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6505                         check_added_monitors!(nodes[0], 1);
6506
6507                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6508                         assert_eq!(events.len(), 1);
6509                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6510                                 assert_eq!(htlcs[0].htlc_id, i);
6511                         } else {
6512                                 assert!(false);
6513                         }
6514                         SendEvent::from_event(events.remove(0))
6515                 };
6516                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6517                 check_added_monitors!(nodes[1], 0);
6518                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6519
6520                 expect_pending_htlcs_forwardable!(nodes[1]);
6521                 expect_payment_received!(nodes[1], our_payment_hash, 100000);
6522         }
6523         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6524         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6525         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6526         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6527                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6528
6529         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6530         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6531 }
6532
6533 #[test]
6534 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6535         //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.
6536         let chanmon_cfgs = create_chanmon_cfgs(2);
6537         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6538         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6539         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6540         let channel_value = 100000;
6541         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6542         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6543
6544         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight, max_in_flight);
6545
6546         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6547         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6548         let logger = test_utils::TestLogger::new();
6549         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &[], max_in_flight+1, TEST_FINAL_CLTV, &logger).unwrap();
6550         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6551                 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)));
6552
6553         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6554         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);
6555
6556         send_payment(&nodes[0], &[&nodes[1]], max_in_flight, max_in_flight);
6557 }
6558
6559 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6560 #[test]
6561 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6562         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6563         let chanmon_cfgs = create_chanmon_cfgs(2);
6564         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6565         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6566         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6567         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6568         let htlc_minimum_msat: u64;
6569         {
6570                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6571                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6572                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6573         }
6574
6575         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6576         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6577         let logger = test_utils::TestLogger::new();
6578         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &[], htlc_minimum_msat, TEST_FINAL_CLTV, &logger).unwrap();
6579         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6580         check_added_monitors!(nodes[0], 1);
6581         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6582         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6583         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6584         assert!(nodes[1].node.list_channels().is_empty());
6585         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6586         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()));
6587         check_added_monitors!(nodes[1], 1);
6588 }
6589
6590 #[test]
6591 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6592         //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
6593         let chanmon_cfgs = create_chanmon_cfgs(2);
6594         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6595         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6596         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6597         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6598         let logger = test_utils::TestLogger::new();
6599
6600         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6601         let channel_reserve = chan_stat.channel_reserve_msat;
6602         let feerate = get_feerate!(nodes[0], chan.2);
6603         // The 2* and +1 are for the fee spike reserve.
6604         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1);
6605
6606         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6607         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6608         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6609         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &[], max_can_send, TEST_FINAL_CLTV, &logger).unwrap();
6610         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6611         check_added_monitors!(nodes[0], 1);
6612         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6613
6614         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6615         // at this time channel-initiatee receivers are not required to enforce that senders
6616         // respect the fee_spike_reserve.
6617         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6618         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6619
6620         assert!(nodes[1].node.list_channels().is_empty());
6621         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6622         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6623         check_added_monitors!(nodes[1], 1);
6624 }
6625
6626 #[test]
6627 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6628         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6629         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6630         let chanmon_cfgs = create_chanmon_cfgs(2);
6631         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6632         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6633         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6634         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6635         let logger = test_utils::TestLogger::new();
6636
6637         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6638         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6639
6640         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6641         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &[], 3999999, TEST_FINAL_CLTV, &logger).unwrap();
6642
6643         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
6644         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6645         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &None, cur_height).unwrap();
6646         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6647
6648         let mut msg = msgs::UpdateAddHTLC {
6649                 channel_id: chan.2,
6650                 htlc_id: 0,
6651                 amount_msat: 1000,
6652                 payment_hash: our_payment_hash,
6653                 cltv_expiry: htlc_cltv,
6654                 onion_routing_packet: onion_packet.clone(),
6655         };
6656
6657         for i in 0..super::channel::OUR_MAX_HTLCS {
6658                 msg.htlc_id = i as u64;
6659                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6660         }
6661         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6662         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6663
6664         assert!(nodes[1].node.list_channels().is_empty());
6665         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6666         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6667         check_added_monitors!(nodes[1], 1);
6668 }
6669
6670 #[test]
6671 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6672         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6673         let chanmon_cfgs = create_chanmon_cfgs(2);
6674         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6675         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6676         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6677         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6678         let logger = test_utils::TestLogger::new();
6679
6680         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6681         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6682         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6683         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6684         check_added_monitors!(nodes[0], 1);
6685         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6686         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6687         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6688
6689         assert!(nodes[1].node.list_channels().is_empty());
6690         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6691         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6692         check_added_monitors!(nodes[1], 1);
6693 }
6694
6695 #[test]
6696 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6697         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6698         let chanmon_cfgs = create_chanmon_cfgs(2);
6699         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6700         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6701         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6702         let logger = test_utils::TestLogger::new();
6703
6704         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6705         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6706         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6707         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6708         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6709         check_added_monitors!(nodes[0], 1);
6710         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6711         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6712         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6713
6714         assert!(nodes[1].node.list_channels().is_empty());
6715         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6716         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6717         check_added_monitors!(nodes[1], 1);
6718 }
6719
6720 #[test]
6721 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6722         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6723         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6724         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6725         let chanmon_cfgs = create_chanmon_cfgs(2);
6726         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6727         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6728         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6729         let logger = test_utils::TestLogger::new();
6730
6731         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6732         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6733         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6734         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6735         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6736         check_added_monitors!(nodes[0], 1);
6737         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6738         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6739
6740         //Disconnect and Reconnect
6741         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6742         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6743         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6744         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6745         assert_eq!(reestablish_1.len(), 1);
6746         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6747         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6748         assert_eq!(reestablish_2.len(), 1);
6749         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6750         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6751         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6752         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6753
6754         //Resend HTLC
6755         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6756         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6757         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6758         check_added_monitors!(nodes[1], 1);
6759         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6760
6761         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6762
6763         assert!(nodes[1].node.list_channels().is_empty());
6764         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6765         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6766         check_added_monitors!(nodes[1], 1);
6767 }
6768
6769 #[test]
6770 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6771         //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.
6772
6773         let chanmon_cfgs = create_chanmon_cfgs(2);
6774         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6775         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6776         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6777         let logger = test_utils::TestLogger::new();
6778         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6779         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6780         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6781         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6782         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6783
6784         check_added_monitors!(nodes[0], 1);
6785         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6786         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6787
6788         let update_msg = msgs::UpdateFulfillHTLC{
6789                 channel_id: chan.2,
6790                 htlc_id: 0,
6791                 payment_preimage: our_payment_preimage,
6792         };
6793
6794         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6795
6796         assert!(nodes[0].node.list_channels().is_empty());
6797         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6798         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()));
6799         check_added_monitors!(nodes[0], 1);
6800 }
6801
6802 #[test]
6803 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6804         //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.
6805
6806         let chanmon_cfgs = create_chanmon_cfgs(2);
6807         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6808         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6809         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6810         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6811         let logger = test_utils::TestLogger::new();
6812
6813         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6814         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6815         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6816         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6817         check_added_monitors!(nodes[0], 1);
6818         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6819         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6820
6821         let update_msg = msgs::UpdateFailHTLC{
6822                 channel_id: chan.2,
6823                 htlc_id: 0,
6824                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6825         };
6826
6827         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6828
6829         assert!(nodes[0].node.list_channels().is_empty());
6830         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6831         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()));
6832         check_added_monitors!(nodes[0], 1);
6833 }
6834
6835 #[test]
6836 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6837         //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.
6838
6839         let chanmon_cfgs = create_chanmon_cfgs(2);
6840         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6841         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6842         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6843         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6844         let logger = test_utils::TestLogger::new();
6845
6846         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6847         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6848         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6849         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6850         check_added_monitors!(nodes[0], 1);
6851         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6852         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6853
6854         let update_msg = msgs::UpdateFailMalformedHTLC{
6855                 channel_id: chan.2,
6856                 htlc_id: 0,
6857                 sha256_of_onion: [1; 32],
6858                 failure_code: 0x8000,
6859         };
6860
6861         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6862
6863         assert!(nodes[0].node.list_channels().is_empty());
6864         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6865         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()));
6866         check_added_monitors!(nodes[0], 1);
6867 }
6868
6869 #[test]
6870 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6871         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6872
6873         let chanmon_cfgs = create_chanmon_cfgs(2);
6874         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6875         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6876         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6877         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6878
6879         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6880
6881         nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6882         check_added_monitors!(nodes[1], 1);
6883
6884         let events = nodes[1].node.get_and_clear_pending_msg_events();
6885         assert_eq!(events.len(), 1);
6886         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6887                 match events[0] {
6888                         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, .. } } => {
6889                                 assert!(update_add_htlcs.is_empty());
6890                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6891                                 assert!(update_fail_htlcs.is_empty());
6892                                 assert!(update_fail_malformed_htlcs.is_empty());
6893                                 assert!(update_fee.is_none());
6894                                 update_fulfill_htlcs[0].clone()
6895                         },
6896                         _ => panic!("Unexpected event"),
6897                 }
6898         };
6899
6900         update_fulfill_msg.htlc_id = 1;
6901
6902         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6903
6904         assert!(nodes[0].node.list_channels().is_empty());
6905         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6906         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6907         check_added_monitors!(nodes[0], 1);
6908 }
6909
6910 #[test]
6911 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6912         //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.
6913
6914         let chanmon_cfgs = create_chanmon_cfgs(2);
6915         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6916         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6917         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6918         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6919
6920         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6921
6922         nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6923         check_added_monitors!(nodes[1], 1);
6924
6925         let events = nodes[1].node.get_and_clear_pending_msg_events();
6926         assert_eq!(events.len(), 1);
6927         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6928                 match events[0] {
6929                         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, .. } } => {
6930                                 assert!(update_add_htlcs.is_empty());
6931                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6932                                 assert!(update_fail_htlcs.is_empty());
6933                                 assert!(update_fail_malformed_htlcs.is_empty());
6934                                 assert!(update_fee.is_none());
6935                                 update_fulfill_htlcs[0].clone()
6936                         },
6937                         _ => panic!("Unexpected event"),
6938                 }
6939         };
6940
6941         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6942
6943         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6944
6945         assert!(nodes[0].node.list_channels().is_empty());
6946         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6947         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6948         check_added_monitors!(nodes[0], 1);
6949 }
6950
6951 #[test]
6952 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6953         //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.
6954
6955         let chanmon_cfgs = create_chanmon_cfgs(2);
6956         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6957         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6958         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6959         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6960         let logger = test_utils::TestLogger::new();
6961
6962         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6963         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6964         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6965         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6966         check_added_monitors!(nodes[0], 1);
6967
6968         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6969         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6970
6971         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6972         check_added_monitors!(nodes[1], 0);
6973         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6974
6975         let events = nodes[1].node.get_and_clear_pending_msg_events();
6976
6977         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6978                 match events[0] {
6979                         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, .. } } => {
6980                                 assert!(update_add_htlcs.is_empty());
6981                                 assert!(update_fulfill_htlcs.is_empty());
6982                                 assert!(update_fail_htlcs.is_empty());
6983                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6984                                 assert!(update_fee.is_none());
6985                                 update_fail_malformed_htlcs[0].clone()
6986                         },
6987                         _ => panic!("Unexpected event"),
6988                 }
6989         };
6990         update_msg.failure_code &= !0x8000;
6991         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6992
6993         assert!(nodes[0].node.list_channels().is_empty());
6994         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6995         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6996         check_added_monitors!(nodes[0], 1);
6997 }
6998
6999 #[test]
7000 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
7001         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
7002         //    * 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.
7003
7004         let chanmon_cfgs = create_chanmon_cfgs(3);
7005         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7006         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7007         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7008         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7009         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7010         let logger = test_utils::TestLogger::new();
7011
7012         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
7013
7014         //First hop
7015         let mut payment_event = {
7016                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
7017                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
7018                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
7019                 check_added_monitors!(nodes[0], 1);
7020                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7021                 assert_eq!(events.len(), 1);
7022                 SendEvent::from_event(events.remove(0))
7023         };
7024         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7025         check_added_monitors!(nodes[1], 0);
7026         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7027         expect_pending_htlcs_forwardable!(nodes[1]);
7028         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7029         assert_eq!(events_2.len(), 1);
7030         check_added_monitors!(nodes[1], 1);
7031         payment_event = SendEvent::from_event(events_2.remove(0));
7032         assert_eq!(payment_event.msgs.len(), 1);
7033
7034         //Second Hop
7035         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7036         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7037         check_added_monitors!(nodes[2], 0);
7038         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7039
7040         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7041         assert_eq!(events_3.len(), 1);
7042         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
7043                 match events_3[0] {
7044                         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 } } => {
7045                                 assert!(update_add_htlcs.is_empty());
7046                                 assert!(update_fulfill_htlcs.is_empty());
7047                                 assert!(update_fail_htlcs.is_empty());
7048                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7049                                 assert!(update_fee.is_none());
7050                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
7051                         },
7052                         _ => panic!("Unexpected event"),
7053                 }
7054         };
7055
7056         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
7057
7058         check_added_monitors!(nodes[1], 0);
7059         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
7060         expect_pending_htlcs_forwardable!(nodes[1]);
7061         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7062         assert_eq!(events_4.len(), 1);
7063
7064         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7065         match events_4[0] {
7066                 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, .. } } => {
7067                         assert!(update_add_htlcs.is_empty());
7068                         assert!(update_fulfill_htlcs.is_empty());
7069                         assert_eq!(update_fail_htlcs.len(), 1);
7070                         assert!(update_fail_malformed_htlcs.is_empty());
7071                         assert!(update_fee.is_none());
7072                 },
7073                 _ => panic!("Unexpected event"),
7074         };
7075
7076         check_added_monitors!(nodes[1], 1);
7077 }
7078
7079 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7080         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7081         // 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
7082         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7083
7084         let chanmon_cfgs = create_chanmon_cfgs(2);
7085         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7086         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7087         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7088         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7089
7090         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7091
7092         // We route 2 dust-HTLCs between A and B
7093         let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7094         let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7095         route_payment(&nodes[0], &[&nodes[1]], 1000000);
7096
7097         // Cache one local commitment tx as previous
7098         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7099
7100         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7101         assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2, &None));
7102         check_added_monitors!(nodes[1], 0);
7103         expect_pending_htlcs_forwardable!(nodes[1]);
7104         check_added_monitors!(nodes[1], 1);
7105
7106         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7107         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7108         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7109         check_added_monitors!(nodes[0], 1);
7110
7111         // Cache one local commitment tx as lastest
7112         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7113
7114         let events = nodes[0].node.get_and_clear_pending_msg_events();
7115         match events[0] {
7116                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7117                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7118                 },
7119                 _ => panic!("Unexpected event"),
7120         }
7121         match events[1] {
7122                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7123                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7124                 },
7125                 _ => panic!("Unexpected event"),
7126         }
7127
7128         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7129         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7130         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7131
7132         if announce_latest {
7133                 connect_block(&nodes[0], &Block { header, txdata: vec![as_last_commitment_tx[0].clone()]}, 1);
7134         } else {
7135                 connect_block(&nodes[0], &Block { header, txdata: vec![as_prev_commitment_tx[0].clone()]}, 1);
7136         }
7137
7138         check_closed_broadcast!(nodes[0], false);
7139         check_added_monitors!(nodes[0], 1);
7140
7141         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7142         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 1, true,  header.block_hash());
7143         let events = nodes[0].node.get_and_clear_pending_events();
7144         // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
7145         assert_eq!(events.len(), 2);
7146         let mut first_failed = false;
7147         for event in events {
7148                 match event {
7149                         Event::PaymentFailed { payment_hash, .. } => {
7150                                 if payment_hash == payment_hash_1 {
7151                                         assert!(!first_failed);
7152                                         first_failed = true;
7153                                 } else {
7154                                         assert_eq!(payment_hash, payment_hash_2);
7155                                 }
7156                         }
7157                         _ => panic!("Unexpected event"),
7158                 }
7159         }
7160 }
7161
7162 #[test]
7163 fn test_failure_delay_dust_htlc_local_commitment() {
7164         do_test_failure_delay_dust_htlc_local_commitment(true);
7165         do_test_failure_delay_dust_htlc_local_commitment(false);
7166 }
7167
7168 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7169         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7170         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7171         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7172         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7173         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7174         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7175
7176         let chanmon_cfgs = create_chanmon_cfgs(3);
7177         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7178         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7179         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7180         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7181
7182         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7183
7184         let (_payment_preimage_1, dust_hash) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7185         let (_payment_preimage_2, non_dust_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7186
7187         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7188         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7189
7190         // We revoked bs_commitment_tx
7191         if revoked {
7192                 let (payment_preimage_3, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7193                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 1_000_000);
7194         }
7195
7196         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7197         let mut timeout_tx = Vec::new();
7198         if local {
7199                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7200                 connect_block(&nodes[0], &Block { header, txdata: vec![as_commitment_tx[0].clone()]}, 1);
7201                 check_closed_broadcast!(nodes[0], false);
7202                 check_added_monitors!(nodes[0], 1);
7203                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7204                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7205                 let parent_hash  = connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 2, true, header.block_hash());
7206                 expect_payment_failed!(nodes[0], dust_hash, true);
7207                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7208                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7209                 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7210                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7211                 connect_block(&nodes[0], &Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
7212                 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7213                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 8, true, header_3.block_hash());
7214                 expect_payment_failed!(nodes[0], non_dust_hash, true);
7215         } else {
7216                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7217                 connect_block(&nodes[0], &Block { header, txdata: vec![bs_commitment_tx[0].clone()]}, 1);
7218                 check_closed_broadcast!(nodes[0], false);
7219                 check_added_monitors!(nodes[0], 1);
7220                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7221                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7222                 let parent_hash  = connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 2, true, header.block_hash());
7223                 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7224                 if !revoked {
7225                         expect_payment_failed!(nodes[0], dust_hash, true);
7226                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7227                         // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7228                         connect_block(&nodes[0], &Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
7229                         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7230                         let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7231                         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 8, true, header_3.block_hash());
7232                         expect_payment_failed!(nodes[0], non_dust_hash, true);
7233                 } else {
7234                         // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7235                         // commitment tx
7236                         let events = nodes[0].node.get_and_clear_pending_events();
7237                         assert_eq!(events.len(), 2);
7238                         let first;
7239                         match events[0] {
7240                                 Event::PaymentFailed { payment_hash, .. } => {
7241                                         if payment_hash == dust_hash { first = true; }
7242                                         else { first = false; }
7243                                 },
7244                                 _ => panic!("Unexpected event"),
7245                         }
7246                         match events[1] {
7247                                 Event::PaymentFailed { payment_hash, .. } => {
7248                                         if first { assert_eq!(payment_hash, non_dust_hash); }
7249                                         else { assert_eq!(payment_hash, dust_hash); }
7250                                 },
7251                                 _ => panic!("Unexpected event"),
7252                         }
7253                 }
7254         }
7255 }
7256
7257 #[test]
7258 fn test_sweep_outbound_htlc_failure_update() {
7259         do_test_sweep_outbound_htlc_failure_update(false, true);
7260         do_test_sweep_outbound_htlc_failure_update(false, false);
7261         do_test_sweep_outbound_htlc_failure_update(true, false);
7262 }
7263
7264 #[test]
7265 fn test_upfront_shutdown_script() {
7266         // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
7267         // enforce it at shutdown message
7268
7269         let mut config = UserConfig::default();
7270         config.channel_options.announced_channel = true;
7271         config.peer_channel_config_limits.force_announced_channel_preference = false;
7272         config.channel_options.commit_upfront_shutdown_pubkey = false;
7273         let user_cfgs = [None, Some(config), None];
7274         let chanmon_cfgs = create_chanmon_cfgs(3);
7275         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7276         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7277         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7278
7279         // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
7280         let flags = InitFeatures::known();
7281         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7282         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7283         let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7284         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7285         // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that  we disconnect peer
7286         nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
7287     assert!(regex::Regex::new(r"Got shutdown request with a scriptpubkey \([A-Fa-f0-9]+\) which did not match their previous scriptpubkey.").unwrap().is_match(check_closed_broadcast!(nodes[2], true).unwrap().data.as_str()));
7288         check_added_monitors!(nodes[2], 1);
7289
7290         // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
7291         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7292         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7293         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7294         // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
7295         nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
7296         let events = nodes[2].node.get_and_clear_pending_msg_events();
7297         assert_eq!(events.len(), 1);
7298         match events[0] {
7299                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7300                 _ => panic!("Unexpected event"),
7301         }
7302
7303         // We test that if case of peer non-signaling we don't enforce committed script at channel opening
7304         let flags_no = InitFeatures::known().clear_upfront_shutdown_script();
7305         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone());
7306         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7307         let mut node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
7308         node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7309         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_1_shutdown);
7310         let events = nodes[1].node.get_and_clear_pending_msg_events();
7311         assert_eq!(events.len(), 1);
7312         match events[0] {
7313                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7314                 _ => panic!("Unexpected event"),
7315         }
7316
7317         // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7318         // channel smoothly, opt-out is from channel initiator here
7319         let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone());
7320         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7321         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7322         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7323         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
7324         let events = nodes[0].node.get_and_clear_pending_msg_events();
7325         assert_eq!(events.len(), 1);
7326         match events[0] {
7327                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7328                 _ => panic!("Unexpected event"),
7329         }
7330
7331         //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7332         //// channel smoothly
7333         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone());
7334         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7335         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7336         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7337         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
7338         let events = nodes[0].node.get_and_clear_pending_msg_events();
7339         assert_eq!(events.len(), 2);
7340         match events[0] {
7341                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7342                 _ => panic!("Unexpected event"),
7343         }
7344         match events[1] {
7345                 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7346                 _ => panic!("Unexpected event"),
7347         }
7348 }
7349
7350 #[test]
7351 fn test_user_configurable_csv_delay() {
7352         // We test our channel constructors yield errors when we pass them absurd csv delay
7353
7354         let mut low_our_to_self_config = UserConfig::default();
7355         low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7356         let mut high_their_to_self_config = UserConfig::default();
7357         high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7358         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7359         let chanmon_cfgs = create_chanmon_cfgs(2);
7360         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7361         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7362         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7363
7364         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7365         let keys_manager: Arc<KeysInterface<ChanKeySigner = EnforcingChannelKeys>> = Arc::new(test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet));
7366         if let Err(error) = Channel::new_outbound(&&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &keys_manager, nodes[1].node.get_our_node_id(), 1000000, 1000000, 0, &low_our_to_self_config) {
7367                 match error {
7368                         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())); },
7369                         _ => panic!("Unexpected event"),
7370                 }
7371         } else { assert!(false) }
7372
7373         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7374         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7375         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7376         open_channel.to_self_delay = 200;
7377         if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &keys_manager, nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel, 0, &low_our_to_self_config) {
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         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7391                 match action {
7392                         &ErrorAction::SendErrorMessage { ref msg } => {
7393                                 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()));
7394                         },
7395                         _ => { assert!(false); }
7396                 }
7397         } else { assert!(false); }
7398
7399         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7400         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7401         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7402         open_channel.to_self_delay = 200;
7403         if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &keys_manager, nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel, 0, &high_their_to_self_config) {
7404                 match error {
7405                         ChannelError::Close(err) => { assert!(regex::Regex::new(r"They wanted our payments to be delayed by a needlessly long period\. Upper limit: \d+\. Actual: \d+").unwrap().is_match(err.as_str())); },
7406                         _ => panic!("Unexpected event"),
7407                 }
7408         } else { assert!(false); }
7409 }
7410
7411 #[test]
7412 fn test_data_loss_protect() {
7413         // We want to be sure that :
7414         // * we don't broadcast our Local Commitment Tx in case of fallen behind
7415         // * we close channel in case of detecting other being fallen behind
7416         // * we are able to claim our own outputs thanks to to_remote being static
7417         let keys_manager;
7418         let persister;
7419         let logger;
7420         let fee_estimator;
7421         let tx_broadcaster;
7422         let chain_source;
7423         let monitor;
7424         let node_state_0;
7425         let chanmon_cfgs = create_chanmon_cfgs(2);
7426         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7427         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7428         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7429
7430         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7431
7432         // Cache node A state before any channel update
7433         let previous_node_state = nodes[0].node.encode();
7434         let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7435         nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut previous_chain_monitor_state).unwrap();
7436
7437         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7438         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7439
7440         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7441         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7442
7443         // Restore node A from previous state
7444         logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7445         let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut ::std::io::Cursor::new(previous_chain_monitor_state.0)).unwrap().1;
7446         chain_source = test_utils::TestChainSource::new(Network::Testnet);
7447         tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
7448         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
7449         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
7450         persister = test_utils::TestPersister{};
7451         monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister);
7452         node_state_0 = {
7453                 let mut channel_monitors = HashMap::new();
7454                 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7455                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut ::std::io::Cursor::new(previous_node_state), ChannelManagerReadArgs {
7456                         keys_manager: &keys_manager,
7457                         fee_estimator: &fee_estimator,
7458                         chain_monitor: &monitor,
7459                         logger: &logger,
7460                         tx_broadcaster: &tx_broadcaster,
7461                         default_config: UserConfig::default(),
7462                         channel_monitors,
7463                 }).unwrap().1
7464         };
7465         nodes[0].node = &node_state_0;
7466         assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7467         nodes[0].chain_monitor = &monitor;
7468         nodes[0].chain_source = &chain_source;
7469
7470         check_added_monitors!(nodes[0], 1);
7471
7472         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7473         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7474
7475         let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7476
7477         // Check we don't broadcast any transactions following learning of per_commitment_point from B
7478         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7479         check_added_monitors!(nodes[0], 1);
7480
7481         {
7482                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7483                 assert_eq!(node_txn.len(), 0);
7484         }
7485
7486         let mut reestablish_1 = Vec::with_capacity(1);
7487         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7488                 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7489                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7490                         reestablish_1.push(msg.clone());
7491                 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7492                 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7493                         match action {
7494                                 &ErrorAction::SendErrorMessage { ref msg } => {
7495                                         assert_eq!(msg.data, "We have fallen behind - we have received proof that if we broadcast remote is going to claim our funds - we can't do any automated broadcasting");
7496                                 },
7497                                 _ => panic!("Unexpected event!"),
7498                         }
7499                 } else {
7500                         panic!("Unexpected event")
7501                 }
7502         }
7503
7504         // Check we close channel detecting A is fallen-behind
7505         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7506         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7507         check_added_monitors!(nodes[1], 1);
7508
7509
7510         // Check A is able to claim to_remote output
7511         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7512         assert_eq!(node_txn.len(), 1);
7513         check_spends!(node_txn[0], chan.3);
7514         assert_eq!(node_txn[0].output.len(), 2);
7515         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
7516         connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[0].clone()]}, 0);
7517         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
7518         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
7519         assert_eq!(spend_txn.len(), 1);
7520         check_spends!(spend_txn[0], node_txn[0]);
7521 }
7522
7523 #[test]
7524 fn test_check_htlc_underpaying() {
7525         // Send payment through A -> B but A is maliciously
7526         // sending a probe payment (i.e less than expected value0
7527         // to B, B should refuse payment.
7528
7529         let chanmon_cfgs = create_chanmon_cfgs(2);
7530         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7531         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7532         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7533
7534         // Create some initial channels
7535         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7536
7537         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 10_000);
7538
7539         // Node 3 is expecting payment of 100_000 but receive 10_000,
7540         // fail htlc like we didn't know the preimage.
7541         nodes[1].node.claim_funds(payment_preimage, &None, 100_000);
7542         nodes[1].node.process_pending_htlc_forwards();
7543
7544         let events = nodes[1].node.get_and_clear_pending_msg_events();
7545         assert_eq!(events.len(), 1);
7546         let (update_fail_htlc, commitment_signed) = match events[0] {
7547                 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 } } => {
7548                         assert!(update_add_htlcs.is_empty());
7549                         assert!(update_fulfill_htlcs.is_empty());
7550                         assert_eq!(update_fail_htlcs.len(), 1);
7551                         assert!(update_fail_malformed_htlcs.is_empty());
7552                         assert!(update_fee.is_none());
7553                         (update_fail_htlcs[0].clone(), commitment_signed)
7554                 },
7555                 _ => panic!("Unexpected event"),
7556         };
7557         check_added_monitors!(nodes[1], 1);
7558
7559         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7560         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7561
7562         // 10_000 msat as u64, followed by a height of 99 as u32
7563         let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7564         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(99));
7565         expect_payment_failed!(nodes[0], payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7566         nodes[1].node.get_and_clear_pending_events();
7567 }
7568
7569 #[test]
7570 fn test_announce_disable_channels() {
7571         // Create 2 channels between A and B. Disconnect B. Call timer_chan_freshness_every_min and check for generated
7572         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7573
7574         let chanmon_cfgs = create_chanmon_cfgs(2);
7575         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7576         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7577         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7578
7579         let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7580         let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7581         let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7582
7583         // Disconnect peers
7584         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7585         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7586
7587         nodes[0].node.timer_chan_freshness_every_min(); // dirty -> stagged
7588         nodes[0].node.timer_chan_freshness_every_min(); // staged -> fresh
7589         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7590         assert_eq!(msg_events.len(), 3);
7591         for e in msg_events {
7592                 match e {
7593                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7594                                 let short_id = msg.contents.short_channel_id;
7595                                 // Check generated channel_update match list in PendingChannelUpdate
7596                                 if short_id != short_id_1 && short_id != short_id_2 && short_id != short_id_3 {
7597                                         panic!("Generated ChannelUpdate for wrong chan!");
7598                                 }
7599                         },
7600                         _ => panic!("Unexpected event"),
7601                 }
7602         }
7603         // Reconnect peers
7604         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7605         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7606         assert_eq!(reestablish_1.len(), 3);
7607         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7608         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7609         assert_eq!(reestablish_2.len(), 3);
7610
7611         // Reestablish chan_1
7612         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7613         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7614         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7615         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7616         // Reestablish chan_2
7617         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7618         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7619         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7620         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7621         // Reestablish chan_3
7622         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7623         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7624         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7625         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7626
7627         nodes[0].node.timer_chan_freshness_every_min();
7628         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7629 }
7630
7631 #[test]
7632 fn test_bump_penalty_txn_on_revoked_commitment() {
7633         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7634         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7635
7636         let chanmon_cfgs = create_chanmon_cfgs(2);
7637         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7638         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7639         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7640
7641         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7642         let logger = test_utils::TestLogger::new();
7643
7644
7645         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7646         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
7647         let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, &Vec::new(), 3000000, 30, &logger).unwrap();
7648         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7649
7650         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7651         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7652         assert_eq!(revoked_txn[0].output.len(), 4);
7653         assert_eq!(revoked_txn[0].input.len(), 1);
7654         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7655         let revoked_txid = revoked_txn[0].txid();
7656
7657         let mut penalty_sum = 0;
7658         for outp in revoked_txn[0].output.iter() {
7659                 if outp.script_pubkey.is_v0_p2wsh() {
7660                         penalty_sum += outp.value;
7661                 }
7662         }
7663
7664         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7665         let header_114 = connect_blocks(&nodes[1], 114, 0, false, Default::default());
7666
7667         // Actually revoke tx by claiming a HTLC
7668         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7669         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7670         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] }, 115);
7671         check_added_monitors!(nodes[1], 1);
7672
7673         // One or more justice tx should have been broadcast, check it
7674         let penalty_1;
7675         let feerate_1;
7676         {
7677                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7678                 assert_eq!(node_txn.len(), 3); // justice tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout (broadcasted from ChannelManager)
7679                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7680                 assert_eq!(node_txn[0].output.len(), 1);
7681                 check_spends!(node_txn[0], revoked_txn[0]);
7682                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7683                 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7684                 penalty_1 = node_txn[0].txid();
7685                 node_txn.clear();
7686         };
7687
7688         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7689         let header = connect_blocks(&nodes[1], 3, 115,  true, header.block_hash());
7690         let mut penalty_2 = penalty_1;
7691         let mut feerate_2 = 0;
7692         {
7693                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7694                 assert_eq!(node_txn.len(), 1);
7695                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7696                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7697                         assert_eq!(node_txn[0].output.len(), 1);
7698                         check_spends!(node_txn[0], revoked_txn[0]);
7699                         penalty_2 = node_txn[0].txid();
7700                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7701                         assert_ne!(penalty_2, penalty_1);
7702                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7703                         feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7704                         // Verify 25% bump heuristic
7705                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7706                         node_txn.clear();
7707                 }
7708         }
7709         assert_ne!(feerate_2, 0);
7710
7711         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7712         connect_blocks(&nodes[1], 3, 118, true, header);
7713         let penalty_3;
7714         let mut feerate_3 = 0;
7715         {
7716                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7717                 assert_eq!(node_txn.len(), 1);
7718                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7719                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7720                         assert_eq!(node_txn[0].output.len(), 1);
7721                         check_spends!(node_txn[0], revoked_txn[0]);
7722                         penalty_3 = node_txn[0].txid();
7723                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7724                         assert_ne!(penalty_3, penalty_2);
7725                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7726                         feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7727                         // Verify 25% bump heuristic
7728                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7729                         node_txn.clear();
7730                 }
7731         }
7732         assert_ne!(feerate_3, 0);
7733
7734         nodes[1].node.get_and_clear_pending_events();
7735         nodes[1].node.get_and_clear_pending_msg_events();
7736 }
7737
7738 #[test]
7739 fn test_bump_penalty_txn_on_revoked_htlcs() {
7740         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7741         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7742
7743         let chanmon_cfgs = create_chanmon_cfgs(2);
7744         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7745         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7746         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7747
7748         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7749         // Lock HTLC in both directions
7750         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3_000_000).0;
7751         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7752
7753         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7754         assert_eq!(revoked_local_txn[0].input.len(), 1);
7755         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7756
7757         // Revoke local commitment tx
7758         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7759
7760         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7761         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7762         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
7763         check_closed_broadcast!(nodes[1], false);
7764         check_added_monitors!(nodes[1], 1);
7765
7766         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7767         assert_eq!(revoked_htlc_txn.len(), 4);
7768         if revoked_htlc_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7769                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7770                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7771                 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7772                 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7773                 assert_eq!(revoked_htlc_txn[1].output.len(), 1);
7774                 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7775         } else if revoked_htlc_txn[1].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7776                 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7777                 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7778                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7779                 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7780                 assert_eq!(revoked_htlc_txn[0].output.len(), 1);
7781                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7782         }
7783
7784         // Broadcast set of revoked txn on A
7785         let header_128 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7786         connect_block(&nodes[0], &Block { header: header_128, txdata: vec![revoked_local_txn[0].clone()] }, 128);
7787         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7788         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7789         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()] }, 129);
7790         let first;
7791         let feerate_1;
7792         let penalty_txn;
7793         {
7794                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7795                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7796                 // Verify claim tx are spending revoked HTLC txn
7797
7798                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7799                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7800                 // which are included in the same block (they are broadcasted because we scan the
7801                 // transactions linearly and generate claims as we go, they likely should be removed in the
7802                 // future).
7803                 assert_eq!(node_txn[0].input.len(), 1);
7804                 check_spends!(node_txn[0], revoked_local_txn[0]);
7805                 assert_eq!(node_txn[1].input.len(), 1);
7806                 check_spends!(node_txn[1], revoked_local_txn[0]);
7807                 assert_eq!(node_txn[2].input.len(), 1);
7808                 check_spends!(node_txn[2], revoked_local_txn[0]);
7809
7810                 // Each of the three justice transactions claim a separate (single) output of the three
7811                 // available, which we check here:
7812                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7813                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7814                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7815
7816                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7817                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7818
7819                 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7820                 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7821                 // a remote commitment tx has already been confirmed).
7822                 check_spends!(node_txn[3], chan.3);
7823
7824                 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7825                 // output, checked above).
7826                 assert_eq!(node_txn[4].input.len(), 2);
7827                 assert_eq!(node_txn[4].output.len(), 1);
7828                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7829
7830                 first = node_txn[4].txid();
7831                 // Store both feerates for later comparison
7832                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[4].output[0].value;
7833                 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7834                 penalty_txn = vec![node_txn[2].clone()];
7835                 node_txn.clear();
7836         }
7837
7838         // Connect one more block to see if bumped penalty are issued for HTLC txn
7839         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7840         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn }, 130);
7841         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7842         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() }, 131);
7843         {
7844                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7845                 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7846
7847                 check_spends!(node_txn[0], revoked_local_txn[0]);
7848                 check_spends!(node_txn[1], revoked_local_txn[0]);
7849                 // Note that these are both bogus - they spend outputs already claimed in block 129:
7850                 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output  {
7851                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7852                 } else {
7853                         assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7854                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7855                 }
7856
7857                 node_txn.clear();
7858         };
7859
7860         // Few more blocks to confirm penalty txn
7861         let header_135 = connect_blocks(&nodes[0], 4, 131, true, header_131.block_hash());
7862         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7863         let header_144 = connect_blocks(&nodes[0], 9, 135, true, header_135);
7864         let node_txn = {
7865                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7866                 assert_eq!(node_txn.len(), 1);
7867
7868                 assert_eq!(node_txn[0].input.len(), 2);
7869                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7870                 // Verify bumped tx is different and 25% bump heuristic
7871                 assert_ne!(first, node_txn[0].txid());
7872                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7873                 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7874                 assert!(feerate_2 * 100 > feerate_1 * 125);
7875                 let txn = vec![node_txn[0].clone()];
7876                 node_txn.clear();
7877                 txn
7878         };
7879         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7880         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7881         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn }, 145);
7882         connect_blocks(&nodes[0], 20, 145, true, header_145.block_hash());
7883         {
7884                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7885                 // We verify than no new transaction has been broadcast because previously
7886                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7887                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7888                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7889                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7890                 // up bumped justice generation.
7891                 assert_eq!(node_txn.len(), 0);
7892                 node_txn.clear();
7893         }
7894         check_closed_broadcast!(nodes[0], false);
7895         check_added_monitors!(nodes[0], 1);
7896 }
7897
7898 #[test]
7899 fn test_bump_penalty_txn_on_remote_commitment() {
7900         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7901         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7902
7903         // Create 2 HTLCs
7904         // Provide preimage for one
7905         // Check aggregation
7906
7907         let chanmon_cfgs = create_chanmon_cfgs(2);
7908         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7909         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7910         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7911
7912         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7913         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7914         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7915
7916         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7917         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7918         assert_eq!(remote_txn[0].output.len(), 4);
7919         assert_eq!(remote_txn[0].input.len(), 1);
7920         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7921
7922         // Claim a HTLC without revocation (provide B monitor with preimage)
7923         nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000);
7924         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7925         connect_block(&nodes[1], &Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
7926         check_added_monitors!(nodes[1], 2);
7927
7928         // One or more claim tx should have been broadcast, check it
7929         let timeout;
7930         let preimage;
7931         let feerate_timeout;
7932         let feerate_preimage;
7933         {
7934                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7935                 assert_eq!(node_txn.len(), 5); // 2 * claim tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout + local HTLC-success (broadcasted from ChannelManager)
7936                 assert_eq!(node_txn[0].input.len(), 1);
7937                 assert_eq!(node_txn[1].input.len(), 1);
7938                 check_spends!(node_txn[0], remote_txn[0]);
7939                 check_spends!(node_txn[1], remote_txn[0]);
7940                 check_spends!(node_txn[2], chan.3);
7941                 check_spends!(node_txn[3], node_txn[2]);
7942                 check_spends!(node_txn[4], node_txn[2]);
7943                 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7944                         timeout = node_txn[0].txid();
7945                         let index = node_txn[0].input[0].previous_output.vout;
7946                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7947                         feerate_timeout = fee * 1000 / node_txn[0].get_weight() as u64;
7948
7949                         preimage = node_txn[1].txid();
7950                         let index = node_txn[1].input[0].previous_output.vout;
7951                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7952                         feerate_preimage = fee * 1000 / node_txn[1].get_weight() as u64;
7953                 } else {
7954                         timeout = node_txn[1].txid();
7955                         let index = node_txn[1].input[0].previous_output.vout;
7956                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7957                         feerate_timeout = fee * 1000 / node_txn[1].get_weight() as u64;
7958
7959                         preimage = node_txn[0].txid();
7960                         let index = node_txn[0].input[0].previous_output.vout;
7961                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7962                         feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7963                 }
7964                 node_txn.clear();
7965         };
7966         assert_ne!(feerate_timeout, 0);
7967         assert_ne!(feerate_preimage, 0);
7968
7969         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7970         connect_blocks(&nodes[1], 15, 1,  true, header.block_hash());
7971         {
7972                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7973                 assert_eq!(node_txn.len(), 2);
7974                 assert_eq!(node_txn[0].input.len(), 1);
7975                 assert_eq!(node_txn[1].input.len(), 1);
7976                 check_spends!(node_txn[0], remote_txn[0]);
7977                 check_spends!(node_txn[1], remote_txn[0]);
7978                 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7979                         let index = node_txn[0].input[0].previous_output.vout;
7980                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7981                         let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7982                         assert!(new_feerate * 100 > feerate_timeout * 125);
7983                         assert_ne!(timeout, node_txn[0].txid());
7984
7985                         let index = node_txn[1].input[0].previous_output.vout;
7986                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7987                         let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7988                         assert!(new_feerate * 100 > feerate_preimage * 125);
7989                         assert_ne!(preimage, node_txn[1].txid());
7990                 } else {
7991                         let index = node_txn[1].input[0].previous_output.vout;
7992                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7993                         let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7994                         assert!(new_feerate * 100 > feerate_timeout * 125);
7995                         assert_ne!(timeout, node_txn[1].txid());
7996
7997                         let index = node_txn[0].input[0].previous_output.vout;
7998                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7999                         let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
8000                         assert!(new_feerate * 100 > feerate_preimage * 125);
8001                         assert_ne!(preimage, node_txn[0].txid());
8002                 }
8003                 node_txn.clear();
8004         }
8005
8006         nodes[1].node.get_and_clear_pending_events();
8007         nodes[1].node.get_and_clear_pending_msg_events();
8008 }
8009
8010 #[test]
8011 fn test_set_outpoints_partial_claiming() {
8012         // - remote party claim tx, new bump tx
8013         // - disconnect remote claiming tx, new bump
8014         // - disconnect tx, see no tx anymore
8015         let chanmon_cfgs = create_chanmon_cfgs(2);
8016         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8017         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8018         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8019
8020         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8021         let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
8022         let payment_preimage_2 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
8023
8024         // Remote commitment txn with 4 outputs: to_local, to_remote, 2 outgoing HTLC
8025         let remote_txn = get_local_commitment_txn!(nodes[1], chan.2);
8026         assert_eq!(remote_txn.len(), 3);
8027         assert_eq!(remote_txn[0].output.len(), 4);
8028         assert_eq!(remote_txn[0].input.len(), 1);
8029         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
8030         check_spends!(remote_txn[1], remote_txn[0]);
8031         check_spends!(remote_txn[2], remote_txn[0]);
8032
8033         // Connect blocks on node A to advance height towards TEST_FINAL_CLTV
8034         let prev_header_100 = connect_blocks(&nodes[1], 100, 0, false, Default::default());
8035         // Provide node A with both preimage
8036         nodes[0].node.claim_funds(payment_preimage_1, &None, 3_000_000);
8037         nodes[0].node.claim_funds(payment_preimage_2, &None, 3_000_000);
8038         check_added_monitors!(nodes[0], 2);
8039         nodes[0].node.get_and_clear_pending_events();
8040         nodes[0].node.get_and_clear_pending_msg_events();
8041
8042         // Connect blocks on node A commitment transaction
8043         let header = BlockHeader { version: 0x20000000, prev_blockhash: prev_header_100, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8044         connect_block(&nodes[0], &Block { header, txdata: vec![remote_txn[0].clone()] }, 101);
8045         check_closed_broadcast!(nodes[0], false);
8046         check_added_monitors!(nodes[0], 1);
8047         // Verify node A broadcast tx claiming both HTLCs
8048         {
8049                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8050                 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-Success*2
8051                 assert_eq!(node_txn.len(), 4);
8052                 check_spends!(node_txn[0], remote_txn[0]);
8053                 check_spends!(node_txn[1], chan.3);
8054                 check_spends!(node_txn[2], node_txn[1]);
8055                 check_spends!(node_txn[3], node_txn[1]);
8056                 assert_eq!(node_txn[0].input.len(), 2);
8057                 node_txn.clear();
8058         }
8059
8060         // Connect blocks on node B
8061         connect_blocks(&nodes[1], 135, 0, false, Default::default());
8062         check_closed_broadcast!(nodes[1], false);
8063         check_added_monitors!(nodes[1], 1);
8064         // Verify node B broadcast 2 HTLC-timeout txn
8065         let partial_claim_tx = {
8066                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8067                 assert_eq!(node_txn.len(), 3);
8068                 check_spends!(node_txn[1], node_txn[0]);
8069                 check_spends!(node_txn[2], node_txn[0]);
8070                 assert_eq!(node_txn[1].input.len(), 1);
8071                 assert_eq!(node_txn[2].input.len(), 1);
8072                 node_txn[1].clone()
8073         };
8074
8075         // Broadcast partial claim on node A, should regenerate a claiming tx with HTLC dropped
8076         let header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8077         connect_block(&nodes[0], &Block { header, txdata: vec![partial_claim_tx.clone()] }, 102);
8078         {
8079                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8080                 assert_eq!(node_txn.len(), 1);
8081                 check_spends!(node_txn[0], remote_txn[0]);
8082                 assert_eq!(node_txn[0].input.len(), 1); //dropped HTLC
8083                 node_txn.clear();
8084         }
8085         nodes[0].node.get_and_clear_pending_msg_events();
8086
8087         // Disconnect last block on node A, should regenerate a claiming tx with HTLC dropped
8088         disconnect_block(&nodes[0], &header, 102);
8089         {
8090                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8091                 assert_eq!(node_txn.len(), 1);
8092                 check_spends!(node_txn[0], remote_txn[0]);
8093                 assert_eq!(node_txn[0].input.len(), 2); //resurrected HTLC
8094                 node_txn.clear();
8095         }
8096
8097         //// Disconnect one more block and then reconnect multiple no transaction should be generated
8098         disconnect_block(&nodes[0], &header, 101);
8099         connect_blocks(&nodes[1], 15, 101, false, prev_header_100);
8100         {
8101                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8102                 assert_eq!(node_txn.len(), 0);
8103                 node_txn.clear();
8104         }
8105 }
8106
8107 #[test]
8108 fn test_counterparty_raa_skip_no_crash() {
8109         // Previously, if our counterparty sent two RAAs in a row without us having provided a
8110         // commitment transaction, we would have happily carried on and provided them the next
8111         // commitment transaction based on one RAA forward. This would probably eventually have led to
8112         // channel closure, but it would not have resulted in funds loss. Still, our
8113         // EnforcingChannelKeys would have paniced as it doesn't like jumps into the future. Here, we
8114         // check simply that the channel is closed in response to such an RAA, but don't check whether
8115         // we decide to punish our counterparty for revoking their funds (as we don't currently
8116         // implement that).
8117         let chanmon_cfgs = create_chanmon_cfgs(2);
8118         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8119         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8120         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8121         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8122
8123         let mut guard = nodes[0].node.channel_state.lock().unwrap();
8124         let keys = &guard.by_id.get_mut(&channel_id).unwrap().holder_keys;
8125         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8126         let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8127                 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8128         let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8129
8130         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8131                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8132         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8133         check_added_monitors!(nodes[1], 1);
8134 }
8135
8136 #[test]
8137 fn test_bump_txn_sanitize_tracking_maps() {
8138         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8139         // verify we clean then right after expiration of ANTI_REORG_DELAY.
8140
8141         let chanmon_cfgs = create_chanmon_cfgs(2);
8142         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8143         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8144         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8145
8146         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8147         // Lock HTLC in both directions
8148         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8149         route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8150
8151         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8152         assert_eq!(revoked_local_txn[0].input.len(), 1);
8153         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8154
8155         // Revoke local commitment tx
8156         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 9_000_000);
8157
8158         // Broadcast set of revoked txn on A
8159         let header_128 = connect_blocks(&nodes[0], 128, 0,  false, Default::default());
8160         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8161
8162         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8163         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_local_txn[0].clone()] }, 129);
8164         check_closed_broadcast!(nodes[0], false);
8165         check_added_monitors!(nodes[0], 1);
8166         let penalty_txn = {
8167                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8168                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8169                 check_spends!(node_txn[0], revoked_local_txn[0]);
8170                 check_spends!(node_txn[1], revoked_local_txn[0]);
8171                 check_spends!(node_txn[2], revoked_local_txn[0]);
8172                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8173                 node_txn.clear();
8174                 penalty_txn
8175         };
8176         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8177         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn }, 130);
8178         connect_blocks(&nodes[0], 5, 130,  false, header_130.block_hash());
8179         {
8180                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap();
8181                 if let Some(monitor) = monitors.get(&OutPoint { txid: chan.3.txid(), index: 0 }) {
8182                         assert!(monitor.onchain_tx_handler.pending_claim_requests.is_empty());
8183                         assert!(monitor.onchain_tx_handler.claimable_outpoints.is_empty());
8184                 }
8185         }
8186 }
8187
8188 #[test]
8189 fn test_override_channel_config() {
8190         let chanmon_cfgs = create_chanmon_cfgs(2);
8191         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8192         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8193         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8194
8195         // Node0 initiates a channel to node1 using the override config.
8196         let mut override_config = UserConfig::default();
8197         override_config.own_channel_config.our_to_self_delay = 200;
8198
8199         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8200
8201         // Assert the channel created by node0 is using the override config.
8202         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8203         assert_eq!(res.channel_flags, 0);
8204         assert_eq!(res.to_self_delay, 200);
8205 }
8206
8207 #[test]
8208 fn test_override_0msat_htlc_minimum() {
8209         let mut zero_config = UserConfig::default();
8210         zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8211         let chanmon_cfgs = create_chanmon_cfgs(2);
8212         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8213         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8214         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8215
8216         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8217         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8218         assert_eq!(res.htlc_minimum_msat, 1);
8219
8220         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8221         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8222         assert_eq!(res.htlc_minimum_msat, 1);
8223 }
8224
8225 #[test]
8226 fn test_simple_payment_secret() {
8227         // Simple test of sending a payment with a payment_secret present. This does not use any AMP
8228         // features, however.
8229         let chanmon_cfgs = create_chanmon_cfgs(3);
8230         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8231         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8232         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8233
8234         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8235         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
8236         let logger = test_utils::TestLogger::new();
8237
8238         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8239         let payment_secret = PaymentSecret([0xdb; 32]);
8240         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8241         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
8242         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2]]], 100000, payment_hash, Some(payment_secret.clone()));
8243         // Claiming with all the correct values but the wrong secret should result in nothing...
8244         assert_eq!(nodes[2].node.claim_funds(payment_preimage, &None, 100_000), false);
8245         assert_eq!(nodes[2].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 100_000), false);
8246         // ...but with the right secret we should be able to claim all the way back
8247         claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage, Some(payment_secret.clone()), 100_000);
8248 }
8249
8250 #[test]
8251 fn test_simple_mpp() {
8252         // Simple test of sending a multi-path payment.
8253         let chanmon_cfgs = create_chanmon_cfgs(4);
8254         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8255         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8256         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8257
8258         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8259         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8260         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8261         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8262         let logger = test_utils::TestLogger::new();
8263
8264         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8265         let payment_secret = PaymentSecret([0xdb; 32]);
8266         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8267         let mut route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
8268         let path = route.paths[0].clone();
8269         route.paths.push(path);
8270         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8271         route.paths[0][0].short_channel_id = chan_1_id;
8272         route.paths[0][1].short_channel_id = chan_3_id;
8273         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8274         route.paths[1][0].short_channel_id = chan_2_id;
8275         route.paths[1][1].short_channel_id = chan_4_id;
8276         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, Some(payment_secret.clone()));
8277         // Claiming with all the correct values but the wrong secret should result in nothing...
8278         assert_eq!(nodes[3].node.claim_funds(payment_preimage, &None, 200_000), false);
8279         assert_eq!(nodes[3].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 200_000), false);
8280         // ...but with the right secret we should be able to claim all the way back
8281         claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage, Some(payment_secret), 200_000);
8282 }
8283
8284 #[test]
8285 fn test_update_err_monitor_lockdown() {
8286         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8287         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8288         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8289         //
8290         // This scenario may happen in a watchtower setup, where watchtower process a block height
8291         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8292         // commitment at same time.
8293
8294         let chanmon_cfgs = create_chanmon_cfgs(2);
8295         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8296         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8297         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8298
8299         // Create some initial channel
8300         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8301         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8302
8303         // Rebalance the network to generate htlc in the two directions
8304         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8305
8306         // Route a HTLC from node 0 to node 1 (but don't settle)
8307         let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8308
8309         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8310         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8311         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8312         let persister = test_utils::TestPersister::new();
8313         let watchtower = {
8314                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap();
8315                 let monitor = monitors.get(&outpoint).unwrap();
8316                 let mut w = test_utils::TestVecWriter(Vec::new());
8317                 monitor.write_for_disk(&mut w).unwrap();
8318                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
8319                                 &mut ::std::io::Cursor::new(&w.0)).unwrap().1;
8320                 assert!(new_monitor == *monitor);
8321                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister);
8322                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8323                 watchtower
8324         };
8325         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8326         watchtower.chain_monitor.block_connected(&header, &[], 200);
8327
8328         // Try to update ChannelMonitor
8329         assert!(nodes[1].node.claim_funds(preimage, &None, 9_000_000));
8330         check_added_monitors!(nodes[1], 1);
8331         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8332         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8333         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8334         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8335                 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8336                         if let Err(_) =  watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8337                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8338                 } else { assert!(false); }
8339         } else { assert!(false); };
8340         // Our local monitor is in-sync and hasn't processed yet timeout
8341         check_added_monitors!(nodes[0], 1);
8342         let events = nodes[0].node.get_and_clear_pending_events();
8343         assert_eq!(events.len(), 1);
8344 }
8345
8346 #[test]
8347 fn test_concurrent_monitor_claim() {
8348         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8349         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8350         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8351         // state N+1 confirms. Alice claims output from state N+1.
8352
8353         let chanmon_cfgs = create_chanmon_cfgs(2);
8354         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8355         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8356         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8357
8358         // Create some initial channel
8359         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8360         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8361
8362         // Rebalance the network to generate htlc in the two directions
8363         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8364
8365         // Route a HTLC from node 0 to node 1 (but don't settle)
8366         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8367
8368         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8369         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8370         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8371         let persister = test_utils::TestPersister::new();
8372         let watchtower_alice = {
8373                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap();
8374                 let monitor = monitors.get(&outpoint).unwrap();
8375                 let mut w = test_utils::TestVecWriter(Vec::new());
8376                 monitor.write_for_disk(&mut w).unwrap();
8377                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
8378                                 &mut ::std::io::Cursor::new(&w.0)).unwrap().1;
8379                 assert!(new_monitor == *monitor);
8380                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister);
8381                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8382                 watchtower
8383         };
8384         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8385         watchtower_alice.chain_monitor.block_connected(&header, &vec![], 135);
8386
8387         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8388         {
8389                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8390                 assert_eq!(txn.len(), 2);
8391                 txn.clear();
8392         }
8393
8394         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8395         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8396         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8397         let persister = test_utils::TestPersister::new();
8398         let watchtower_bob = {
8399                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap();
8400                 let monitor = monitors.get(&outpoint).unwrap();
8401                 let mut w = test_utils::TestVecWriter(Vec::new());
8402                 monitor.write_for_disk(&mut w).unwrap();
8403                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
8404                                 &mut ::std::io::Cursor::new(&w.0)).unwrap().1;
8405                 assert!(new_monitor == *monitor);
8406                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister);
8407                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8408                 watchtower
8409         };
8410         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8411         watchtower_bob.chain_monitor.block_connected(&header, &vec![], 134);
8412
8413         // Route another payment to generate another update with still previous HTLC pending
8414         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
8415         {
8416                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
8417                 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, &Vec::new(), 3000000 , TEST_FINAL_CLTV, &logger).unwrap();
8418                 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
8419         }
8420         check_added_monitors!(nodes[1], 1);
8421
8422         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8423         assert_eq!(updates.update_add_htlcs.len(), 1);
8424         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8425         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8426                 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8427                         // Watchtower Alice should already have seen the block and reject the update
8428                         if let Err(_) =  watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8429                         if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8430                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8431                 } else { assert!(false); }
8432         } else { assert!(false); };
8433         // Our local monitor is in-sync and hasn't processed yet timeout
8434         check_added_monitors!(nodes[0], 1);
8435
8436         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8437         watchtower_bob.chain_monitor.block_connected(&header, &vec![], 135);
8438
8439         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8440         let bob_state_y;
8441         {
8442                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8443                 assert_eq!(txn.len(), 2);
8444                 bob_state_y = txn[0].clone();
8445                 txn.clear();
8446         };
8447
8448         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8449         watchtower_alice.chain_monitor.block_connected(&header, &vec![(0, &bob_state_y)], 136);
8450         {
8451                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8452                 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8453                 // the onchain detection of the HTLC output
8454                 assert_eq!(htlc_txn.len(), 2);
8455                 check_spends!(htlc_txn[0], bob_state_y);
8456                 check_spends!(htlc_txn[1], bob_state_y);
8457         }
8458 }
8459
8460 #[test]
8461 fn test_htlc_no_detection() {
8462         // This test is a mutation to underscore the detection logic bug we had
8463         // before #653. HTLC value routed is above the remaining balance, thus
8464         // inverting HTLC and `to_remote` output. HTLC will come second and
8465         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8466         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8467         // outputs order detection for correct spending children filtring.
8468
8469         let chanmon_cfgs = create_chanmon_cfgs(2);
8470         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8471         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8472         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8473
8474         // Create some initial channels
8475         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8476
8477         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000, 1_000_000);
8478         let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8479         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8480         assert_eq!(local_txn[0].input.len(), 1);
8481         assert_eq!(local_txn[0].output.len(), 3);
8482         check_spends!(local_txn[0], chan_1.3);
8483
8484         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8485         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8486         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] }, 200);
8487         // We deliberately connect the local tx twice as this should provoke a failure calling
8488         // this test before #653 fix.
8489         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] }, 200);
8490         check_closed_broadcast!(nodes[0], false);
8491         check_added_monitors!(nodes[0], 1);
8492
8493         let htlc_timeout = {
8494                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8495                 assert_eq!(node_txn[0].input.len(), 1);
8496                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8497                 check_spends!(node_txn[0], local_txn[0]);
8498                 node_txn[0].clone()
8499         };
8500
8501         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8502         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
8503         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
8504         expect_payment_failed!(nodes[0], our_payment_hash, true);
8505 }