Merge pull request #764 from lightning-signer/revoke-enforcement
[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};
32 use util::config::UserConfig;
33
34 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
35 use bitcoin::hash_types::{Txid, BlockHash};
36 use bitcoin::util::bip143;
37 use bitcoin::util::address::Address;
38 use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
39 use bitcoin::blockdata::block::{Block, BlockHeader};
40 use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType};
41 use bitcoin::blockdata::script::{Builder, Script};
42 use bitcoin::blockdata::opcodes;
43 use bitcoin::blockdata::constants::genesis_block;
44 use bitcoin::network::constants::Network;
45
46 use bitcoin::hashes::sha256::Hash as Sha256;
47 use bitcoin::hashes::Hash;
48
49 use bitcoin::secp256k1::{Secp256k1, Message};
50 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
51
52 use regex;
53
54 use std::collections::{BTreeSet, HashMap, HashSet};
55 use std::default::Default;
56 use std::sync::Mutex;
57 use std::sync::atomic::Ordering;
58 use std::mem;
59
60 use ln::functional_test_utils::*;
61 use ln::chan_utils::CommitmentTransaction;
62
63 #[test]
64 fn test_insane_channel_opens() {
65         // Stand up a network of 2 nodes
66         let chanmon_cfgs = create_chanmon_cfgs(2);
67         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
68         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
69         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
70
71         // Instantiate channel parameters where we push the maximum msats given our
72         // funding satoshis
73         let channel_value_sat = 31337; // same as funding satoshis
74         let channel_reserve_satoshis = Channel::<EnforcingChannelKeys>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
75         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
76
77         // Have node0 initiate a channel to node1 with aforementioned parameters
78         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
79
80         // Extract the channel open message from node0 to node1
81         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
82
83         // Test helper that asserts we get the correct error string given a mutator
84         // that supposedly makes the channel open message insane
85         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
86                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
87                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
88                 assert_eq!(msg_events.len(), 1);
89                 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
90                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
91                         match action {
92                                 &ErrorAction::SendErrorMessage { .. } => {
93                                         nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
94                                 },
95                                 _ => panic!("unexpected event!"),
96                         }
97                 } else { assert!(false); }
98         };
99
100         use ln::channel::MAX_FUNDING_SATOSHIS;
101         use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
102
103         // Test all mutations that would make the channel open message insane
104         insane_open_helper(format!("Funding must be smaller than {}. It was {}", MAX_FUNDING_SATOSHIS, MAX_FUNDING_SATOSHIS).as_str(), |mut msg| { msg.funding_satoshis = MAX_FUNDING_SATOSHIS; msg });
105
106         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
107
108         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 });
109
110         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
111
112         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 });
113
114         insane_open_helper(r"Minimum htlc value \(\d+\) was larger than full channel value \(\d+\)", |mut msg| { msg.htlc_minimum_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000; msg });
115
116         insane_open_helper("They wanted our payments to be delayed by a needlessly long period", |mut msg| { msg.to_self_delay = MAX_LOCAL_BREAKDOWN_TIMEOUT + 1; msg });
117
118         insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
119
120         insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
121 }
122
123 #[test]
124 fn test_async_inbound_update_fee() {
125         let chanmon_cfgs = create_chanmon_cfgs(2);
126         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
127         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
128         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
129         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
130         let logger = test_utils::TestLogger::new();
131         let channel_id = chan.2;
132
133         // balancing
134         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
135
136         // A                                        B
137         // update_fee                            ->
138         // send (1) commitment_signed            -.
139         //                                       <- update_add_htlc/commitment_signed
140         // send (2) RAA (awaiting remote revoke) -.
141         // (1) commitment_signed is delivered    ->
142         //                                       .- send (3) RAA (awaiting remote revoke)
143         // (2) RAA is delivered                  ->
144         //                                       .- send (4) commitment_signed
145         //                                       <- (3) RAA is delivered
146         // send (5) commitment_signed            -.
147         //                                       <- (4) commitment_signed is delivered
148         // send (6) RAA                          -.
149         // (5) commitment_signed is delivered    ->
150         //                                       <- RAA
151         // (6) RAA is delivered                  ->
152
153         // First nodes[0] generates an update_fee
154         nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
155         check_added_monitors!(nodes[0], 1);
156
157         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
158         assert_eq!(events_0.len(), 1);
159         let (update_msg, commitment_signed) = match events_0[0] { // (1)
160                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
161                         (update_fee.as_ref(), commitment_signed)
162                 },
163                 _ => panic!("Unexpected event"),
164         };
165
166         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
167
168         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
169         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
170         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
171         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();
172         check_added_monitors!(nodes[1], 1);
173
174         let payment_event = {
175                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
176                 assert_eq!(events_1.len(), 1);
177                 SendEvent::from_event(events_1.remove(0))
178         };
179         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
180         assert_eq!(payment_event.msgs.len(), 1);
181
182         // ...now when the messages get delivered everyone should be happy
183         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
184         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
185         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
186         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
187         check_added_monitors!(nodes[0], 1);
188
189         // deliver(1), generate (3):
190         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
191         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
192         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
193         check_added_monitors!(nodes[1], 1);
194
195         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
196         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
197         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
198         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
199         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
200         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
201         assert!(bs_update.update_fee.is_none()); // (4)
202         check_added_monitors!(nodes[1], 1);
203
204         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
205         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
206         assert!(as_update.update_add_htlcs.is_empty()); // (5)
207         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
208         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
209         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
210         assert!(as_update.update_fee.is_none()); // (5)
211         check_added_monitors!(nodes[0], 1);
212
213         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
214         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
215         // only (6) so get_event_msg's assert(len == 1) passes
216         check_added_monitors!(nodes[0], 1);
217
218         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
219         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
220         check_added_monitors!(nodes[1], 1);
221
222         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
223         check_added_monitors!(nodes[0], 1);
224
225         let events_2 = nodes[0].node.get_and_clear_pending_events();
226         assert_eq!(events_2.len(), 1);
227         match events_2[0] {
228                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
229                 _ => panic!("Unexpected event"),
230         }
231
232         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
233         check_added_monitors!(nodes[1], 1);
234 }
235
236 #[test]
237 fn test_update_fee_unordered_raa() {
238         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
239         // crash in an earlier version of the update_fee patch)
240         let chanmon_cfgs = create_chanmon_cfgs(2);
241         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
242         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
243         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
244         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
245         let channel_id = chan.2;
246         let logger = test_utils::TestLogger::new();
247
248         // balancing
249         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
250
251         // First nodes[0] generates an update_fee
252         nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
253         check_added_monitors!(nodes[0], 1);
254
255         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
256         assert_eq!(events_0.len(), 1);
257         let update_msg = match events_0[0] { // (1)
258                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
259                         update_fee.as_ref()
260                 },
261                 _ => panic!("Unexpected event"),
262         };
263
264         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
265
266         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
267         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
268         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
269         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();
270         check_added_monitors!(nodes[1], 1);
271
272         let payment_event = {
273                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
274                 assert_eq!(events_1.len(), 1);
275                 SendEvent::from_event(events_1.remove(0))
276         };
277         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
278         assert_eq!(payment_event.msgs.len(), 1);
279
280         // ...now when the messages get delivered everyone should be happy
281         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
282         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
283         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
284         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
285         check_added_monitors!(nodes[0], 1);
286
287         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
288         check_added_monitors!(nodes[1], 1);
289
290         // We can't continue, sadly, because our (1) now has a bogus signature
291 }
292
293 #[test]
294 fn test_multi_flight_update_fee() {
295         let chanmon_cfgs = create_chanmon_cfgs(2);
296         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
297         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
298         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
299         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
300         let channel_id = chan.2;
301
302         // A                                        B
303         // update_fee/commitment_signed          ->
304         //                                       .- send (1) RAA and (2) commitment_signed
305         // update_fee (never committed)          ->
306         // (3) update_fee                        ->
307         // We have to manually generate the above update_fee, it is allowed by the protocol but we
308         // don't track which updates correspond to which revoke_and_ack responses so we're in
309         // AwaitingRAA mode and will not generate the update_fee yet.
310         //                                       <- (1) RAA delivered
311         // (3) is generated and send (4) CS      -.
312         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
313         // know the per_commitment_point to use for it.
314         //                                       <- (2) commitment_signed delivered
315         // revoke_and_ack                        ->
316         //                                          B should send no response here
317         // (4) commitment_signed delivered       ->
318         //                                       <- RAA/commitment_signed delivered
319         // revoke_and_ack                        ->
320
321         // First nodes[0] generates an update_fee
322         let initial_feerate = get_feerate!(nodes[0], channel_id);
323         nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
324         check_added_monitors!(nodes[0], 1);
325
326         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
327         assert_eq!(events_0.len(), 1);
328         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
329                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
330                         (update_fee.as_ref().unwrap(), commitment_signed)
331                 },
332                 _ => panic!("Unexpected event"),
333         };
334
335         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
336         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
337         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
338         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
339         check_added_monitors!(nodes[1], 1);
340
341         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
342         // transaction:
343         nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
344         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
345         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
346
347         // Create the (3) update_fee message that nodes[0] will generate before it does...
348         let mut update_msg_2 = msgs::UpdateFee {
349                 channel_id: update_msg_1.channel_id.clone(),
350                 feerate_per_kw: (initial_feerate + 30) as u32,
351         };
352
353         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
354
355         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
356         // Deliver (3)
357         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
358
359         // Deliver (1), generating (3) and (4)
360         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
361         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
362         check_added_monitors!(nodes[0], 1);
363         assert!(as_second_update.update_add_htlcs.is_empty());
364         assert!(as_second_update.update_fulfill_htlcs.is_empty());
365         assert!(as_second_update.update_fail_htlcs.is_empty());
366         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
367         // Check that the update_fee newly generated matches what we delivered:
368         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
369         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
370
371         // Deliver (2) commitment_signed
372         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
373         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
374         check_added_monitors!(nodes[0], 1);
375         // No commitment_signed so get_event_msg's assert(len == 1) passes
376
377         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
378         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
379         check_added_monitors!(nodes[1], 1);
380
381         // Delever (4)
382         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
383         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
384         check_added_monitors!(nodes[1], 1);
385
386         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
387         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
388         check_added_monitors!(nodes[0], 1);
389
390         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
391         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
392         // No commitment_signed so get_event_msg's assert(len == 1) passes
393         check_added_monitors!(nodes[0], 1);
394
395         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
396         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
397         check_added_monitors!(nodes[1], 1);
398 }
399
400 #[test]
401 fn test_1_conf_open() {
402         // Previously, if the minium_depth config was set to 1, we'd never send a funding_locked. This
403         // tests that we properly send one in that case.
404         let mut alice_config = UserConfig::default();
405         alice_config.own_channel_config.minimum_depth = 1;
406         alice_config.channel_options.announced_channel = true;
407         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
408         let mut bob_config = UserConfig::default();
409         bob_config.own_channel_config.minimum_depth = 1;
410         bob_config.channel_options.announced_channel = true;
411         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
412         let chanmon_cfgs = create_chanmon_cfgs(2);
413         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
414         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(alice_config), Some(bob_config)]);
415         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
416
417         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
418         let block = Block {
419                 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
420                 txdata: vec![tx],
421         };
422         connect_block(&nodes[1], &block, 1);
423         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()));
424
425         connect_block(&nodes[0], &block, 1);
426         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
427         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
428
429         for node in nodes {
430                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
431                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
432                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
433         }
434 }
435
436 fn do_test_sanity_on_in_flight_opens(steps: u8) {
437         // Previously, we had issues deserializing channels when we hadn't connected the first block
438         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
439         // serialization round-trips and simply do steps towards opening a channel and then drop the
440         // Node objects.
441
442         let chanmon_cfgs = create_chanmon_cfgs(2);
443         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
444         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
445         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
446
447         if steps & 0b1000_0000 != 0{
448                 let block = Block {
449                         header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
450                         txdata: vec![],
451                 };
452                 connect_block(&nodes[0], &block, 1);
453                 connect_block(&nodes[1], &block, 1);
454         }
455
456         if steps & 0x0f == 0 { return; }
457         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
458         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
459
460         if steps & 0x0f == 1 { return; }
461         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
462         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
463
464         if steps & 0x0f == 2 { return; }
465         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
466
467         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
468
469         if steps & 0x0f == 3 { return; }
470         nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
471         check_added_monitors!(nodes[0], 0);
472         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
473
474         if steps & 0x0f == 4 { return; }
475         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
476         {
477                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
478                 assert_eq!(added_monitors.len(), 1);
479                 assert_eq!(added_monitors[0].0, funding_output);
480                 added_monitors.clear();
481         }
482         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
483
484         if steps & 0x0f == 5 { return; }
485         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
486         {
487                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
488                 assert_eq!(added_monitors.len(), 1);
489                 assert_eq!(added_monitors[0].0, funding_output);
490                 added_monitors.clear();
491         }
492
493         let events_4 = nodes[0].node.get_and_clear_pending_events();
494         assert_eq!(events_4.len(), 1);
495         match events_4[0] {
496                 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
497                         assert_eq!(user_channel_id, 42);
498                         assert_eq!(*funding_txo, funding_output);
499                 },
500                 _ => panic!("Unexpected event"),
501         };
502
503         if steps & 0x0f == 6 { return; }
504         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx);
505
506         if steps & 0x0f == 7 { return; }
507         confirm_transaction(&nodes[0], &tx);
508         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
509 }
510
511 #[test]
512 fn test_sanity_on_in_flight_opens() {
513         do_test_sanity_on_in_flight_opens(0);
514         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
515         do_test_sanity_on_in_flight_opens(1);
516         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
517         do_test_sanity_on_in_flight_opens(2);
518         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
519         do_test_sanity_on_in_flight_opens(3);
520         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
521         do_test_sanity_on_in_flight_opens(4);
522         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
523         do_test_sanity_on_in_flight_opens(5);
524         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
525         do_test_sanity_on_in_flight_opens(6);
526         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
527         do_test_sanity_on_in_flight_opens(7);
528         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
529         do_test_sanity_on_in_flight_opens(8);
530         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
531 }
532
533 #[test]
534 fn test_update_fee_vanilla() {
535         let chanmon_cfgs = create_chanmon_cfgs(2);
536         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
537         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
538         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
539         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
540         let channel_id = chan.2;
541
542         let feerate = get_feerate!(nodes[0], channel_id);
543         nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
544         check_added_monitors!(nodes[0], 1);
545
546         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
547         assert_eq!(events_0.len(), 1);
548         let (update_msg, commitment_signed) = match events_0[0] {
549                         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 } } => {
550                         (update_fee.as_ref(), commitment_signed)
551                 },
552                 _ => panic!("Unexpected event"),
553         };
554         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
555
556         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
557         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
558         check_added_monitors!(nodes[1], 1);
559
560         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
561         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
562         check_added_monitors!(nodes[0], 1);
563
564         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
565         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
566         // No commitment_signed so get_event_msg's assert(len == 1) passes
567         check_added_monitors!(nodes[0], 1);
568
569         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
570         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
571         check_added_monitors!(nodes[1], 1);
572 }
573
574 #[test]
575 fn test_update_fee_that_funder_cannot_afford() {
576         let chanmon_cfgs = create_chanmon_cfgs(2);
577         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
578         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
579         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
580         let channel_value = 1888;
581         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000, InitFeatures::known(), InitFeatures::known());
582         let channel_id = chan.2;
583
584         let feerate = 260;
585         nodes[0].node.update_fee(channel_id, feerate).unwrap();
586         check_added_monitors!(nodes[0], 1);
587         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
588
589         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
590
591         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
592
593         //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
594         //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
595         {
596                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
597
598                 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
599                 let num_htlcs = commitment_tx.output.len() - 2;
600                 let total_fee: u64 = feerate as u64 * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
601                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
602                 actual_fee = channel_value - actual_fee;
603                 assert_eq!(total_fee, actual_fee);
604         }
605
606         //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
607         //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
608         nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
609         check_added_monitors!(nodes[0], 1);
610
611         let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
612
613         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap());
614
615         //While producing the commitment_signed response after handling a received update_fee request the
616         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
617         //Should produce and error.
618         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed);
619         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
620         check_added_monitors!(nodes[1], 1);
621         check_closed_broadcast!(nodes[1], true);
622 }
623
624 #[test]
625 fn test_update_fee_with_fundee_update_add_htlc() {
626         let chanmon_cfgs = create_chanmon_cfgs(2);
627         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
628         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
629         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
630         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
631         let channel_id = chan.2;
632         let logger = test_utils::TestLogger::new();
633
634         // balancing
635         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
636
637         let feerate = get_feerate!(nodes[0], channel_id);
638         nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
639         check_added_monitors!(nodes[0], 1);
640
641         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
642         assert_eq!(events_0.len(), 1);
643         let (update_msg, commitment_signed) = match events_0[0] {
644                         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 } } => {
645                         (update_fee.as_ref(), commitment_signed)
646                 },
647                 _ => panic!("Unexpected event"),
648         };
649         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
650         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
651         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
652         check_added_monitors!(nodes[1], 1);
653
654         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
655         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
656         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();
657
658         // nothing happens since node[1] is in AwaitingRemoteRevoke
659         nodes[1].node.send_payment(&route, our_payment_hash, &None).unwrap();
660         {
661                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
662                 assert_eq!(added_monitors.len(), 0);
663                 added_monitors.clear();
664         }
665         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
666         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
667         // node[1] has nothing to do
668
669         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
670         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
671         check_added_monitors!(nodes[0], 1);
672
673         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
674         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
675         // No commitment_signed so get_event_msg's assert(len == 1) passes
676         check_added_monitors!(nodes[0], 1);
677         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
678         check_added_monitors!(nodes[1], 1);
679         // AwaitingRemoteRevoke ends here
680
681         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
682         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
683         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
684         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
685         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
686         assert_eq!(commitment_update.update_fee.is_none(), true);
687
688         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
689         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
690         check_added_monitors!(nodes[0], 1);
691         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
692
693         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
694         check_added_monitors!(nodes[1], 1);
695         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
696
697         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
698         check_added_monitors!(nodes[1], 1);
699         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
700         // No commitment_signed so get_event_msg's assert(len == 1) passes
701
702         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
703         check_added_monitors!(nodes[0], 1);
704         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
705
706         expect_pending_htlcs_forwardable!(nodes[0]);
707
708         let events = nodes[0].node.get_and_clear_pending_events();
709         assert_eq!(events.len(), 1);
710         match events[0] {
711                 Event::PaymentReceived { .. } => { },
712                 _ => panic!("Unexpected event"),
713         };
714
715         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage, 800_000);
716
717         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000, 800_000);
718         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000, 800_000);
719         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
720 }
721
722 #[test]
723 fn test_update_fee() {
724         let chanmon_cfgs = create_chanmon_cfgs(2);
725         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
726         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
727         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
728         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
729         let channel_id = chan.2;
730
731         // A                                        B
732         // (1) update_fee/commitment_signed      ->
733         //                                       <- (2) revoke_and_ack
734         //                                       .- send (3) commitment_signed
735         // (4) update_fee/commitment_signed      ->
736         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
737         //                                       <- (3) commitment_signed delivered
738         // send (6) revoke_and_ack               -.
739         //                                       <- (5) deliver revoke_and_ack
740         // (6) deliver revoke_and_ack            ->
741         //                                       .- send (7) commitment_signed in response to (4)
742         //                                       <- (7) deliver commitment_signed
743         // revoke_and_ack                        ->
744
745         // Create and deliver (1)...
746         let feerate = get_feerate!(nodes[0], channel_id);
747         nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
748         check_added_monitors!(nodes[0], 1);
749
750         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
751         assert_eq!(events_0.len(), 1);
752         let (update_msg, commitment_signed) = match events_0[0] {
753                         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 } } => {
754                         (update_fee.as_ref(), commitment_signed)
755                 },
756                 _ => panic!("Unexpected event"),
757         };
758         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
759
760         // Generate (2) and (3):
761         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
762         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
763         check_added_monitors!(nodes[1], 1);
764
765         // Deliver (2):
766         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
767         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
768         check_added_monitors!(nodes[0], 1);
769
770         // Create and deliver (4)...
771         nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
772         check_added_monitors!(nodes[0], 1);
773         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
774         assert_eq!(events_0.len(), 1);
775         let (update_msg, commitment_signed) = match events_0[0] {
776                         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 } } => {
777                         (update_fee.as_ref(), commitment_signed)
778                 },
779                 _ => panic!("Unexpected event"),
780         };
781
782         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
783         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
784         check_added_monitors!(nodes[1], 1);
785         // ... creating (5)
786         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
787         // No commitment_signed so get_event_msg's assert(len == 1) passes
788
789         // Handle (3), creating (6):
790         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
791         check_added_monitors!(nodes[0], 1);
792         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
793         // No commitment_signed so get_event_msg's assert(len == 1) passes
794
795         // Deliver (5):
796         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
797         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
798         check_added_monitors!(nodes[0], 1);
799
800         // Deliver (6), creating (7):
801         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
802         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
803         assert!(commitment_update.update_add_htlcs.is_empty());
804         assert!(commitment_update.update_fulfill_htlcs.is_empty());
805         assert!(commitment_update.update_fail_htlcs.is_empty());
806         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
807         assert!(commitment_update.update_fee.is_none());
808         check_added_monitors!(nodes[1], 1);
809
810         // Deliver (7)
811         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
812         check_added_monitors!(nodes[0], 1);
813         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
814         // No commitment_signed so get_event_msg's assert(len == 1) passes
815
816         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
817         check_added_monitors!(nodes[1], 1);
818         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
819
820         assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
821         assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
822         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
823 }
824
825 #[test]
826 fn pre_funding_lock_shutdown_test() {
827         // Test sending a shutdown prior to funding_locked after funding generation
828         let chanmon_cfgs = create_chanmon_cfgs(2);
829         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
830         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
831         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
832         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0, InitFeatures::known(), InitFeatures::known());
833         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
834         connect_block(&nodes[0], &Block { header, txdata: vec![tx.clone()]}, 1);
835         connect_block(&nodes[1], &Block { header, txdata: vec![tx.clone()]}, 1);
836
837         nodes[0].node.close_channel(&OutPoint { txid: tx.txid(), index: 0 }.to_channel_id()).unwrap();
838         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
839         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
840         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
841         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
842
843         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
844         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
845         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
846         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
847         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
848         assert!(node_0_none.is_none());
849
850         assert!(nodes[0].node.list_channels().is_empty());
851         assert!(nodes[1].node.list_channels().is_empty());
852 }
853
854 #[test]
855 fn updates_shutdown_wait() {
856         // Test sending a shutdown with outstanding updates pending
857         let chanmon_cfgs = create_chanmon_cfgs(3);
858         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
859         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
860         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
861         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
862         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
863         let logger = test_utils::TestLogger::new();
864
865         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
866
867         nodes[0].node.close_channel(&chan_1.2).unwrap();
868         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
869         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
870         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
871         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
872
873         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
874         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
875
876         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
877
878         let net_graph_msg_handler0 = &nodes[0].net_graph_msg_handler;
879         let net_graph_msg_handler1 = &nodes[1].net_graph_msg_handler;
880         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();
881         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();
882         unwrap_send_err!(nodes[0].node.send_payment(&route_1, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
883         unwrap_send_err!(nodes[1].node.send_payment(&route_2, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
884
885         assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
886         check_added_monitors!(nodes[2], 1);
887         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
888         assert!(updates.update_add_htlcs.is_empty());
889         assert!(updates.update_fail_htlcs.is_empty());
890         assert!(updates.update_fail_malformed_htlcs.is_empty());
891         assert!(updates.update_fee.is_none());
892         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
893         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
894         check_added_monitors!(nodes[1], 1);
895         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
896         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
897
898         assert!(updates_2.update_add_htlcs.is_empty());
899         assert!(updates_2.update_fail_htlcs.is_empty());
900         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
901         assert!(updates_2.update_fee.is_none());
902         assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
903         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
904         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
905
906         let events = nodes[0].node.get_and_clear_pending_events();
907         assert_eq!(events.len(), 1);
908         match events[0] {
909                 Event::PaymentSent { ref payment_preimage } => {
910                         assert_eq!(our_payment_preimage, *payment_preimage);
911                 },
912                 _ => panic!("Unexpected event"),
913         }
914
915         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
916         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
917         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
918         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
919         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
920         assert!(node_0_none.is_none());
921
922         assert!(nodes[0].node.list_channels().is_empty());
923
924         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
925         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
926         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
927         assert!(nodes[1].node.list_channels().is_empty());
928         assert!(nodes[2].node.list_channels().is_empty());
929 }
930
931 #[test]
932 fn htlc_fail_async_shutdown() {
933         // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
934         let chanmon_cfgs = create_chanmon_cfgs(3);
935         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
936         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
937         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
938         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
939         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
940         let logger = test_utils::TestLogger::new();
941
942         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
943         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
944         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();
945         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
946         check_added_monitors!(nodes[0], 1);
947         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
948         assert_eq!(updates.update_add_htlcs.len(), 1);
949         assert!(updates.update_fulfill_htlcs.is_empty());
950         assert!(updates.update_fail_htlcs.is_empty());
951         assert!(updates.update_fail_malformed_htlcs.is_empty());
952         assert!(updates.update_fee.is_none());
953
954         nodes[1].node.close_channel(&chan_1.2).unwrap();
955         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
956         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
957         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
958
959         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
960         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
961         check_added_monitors!(nodes[1], 1);
962         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
963         commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
964
965         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
966         assert!(updates_2.update_add_htlcs.is_empty());
967         assert!(updates_2.update_fulfill_htlcs.is_empty());
968         assert_eq!(updates_2.update_fail_htlcs.len(), 1);
969         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
970         assert!(updates_2.update_fee.is_none());
971
972         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]);
973         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
974
975         expect_payment_failed!(nodes[0], our_payment_hash, false);
976
977         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
978         assert_eq!(msg_events.len(), 2);
979         let node_0_closing_signed = match msg_events[0] {
980                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
981                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
982                         (*msg).clone()
983                 },
984                 _ => panic!("Unexpected event"),
985         };
986         match msg_events[1] {
987                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
988                         assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
989                 },
990                 _ => panic!("Unexpected event"),
991         }
992
993         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
994         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
995         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
996         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
997         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
998         assert!(node_0_none.is_none());
999
1000         assert!(nodes[0].node.list_channels().is_empty());
1001
1002         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1003         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1004         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1005         assert!(nodes[1].node.list_channels().is_empty());
1006         assert!(nodes[2].node.list_channels().is_empty());
1007 }
1008
1009 fn do_test_shutdown_rebroadcast(recv_count: u8) {
1010         // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
1011         // messages delivered prior to disconnect
1012         let chanmon_cfgs = create_chanmon_cfgs(3);
1013         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1014         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1015         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1016         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1017         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1018
1019         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
1020
1021         nodes[1].node.close_channel(&chan_1.2).unwrap();
1022         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1023         if recv_count > 0 {
1024                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
1025                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1026                 if recv_count > 1 {
1027                         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
1028                 }
1029         }
1030
1031         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1032         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1033
1034         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1035         let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1036         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1037         let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1038
1039         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish);
1040         let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1041         assert!(node_1_shutdown == node_1_2nd_shutdown);
1042
1043         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish);
1044         let node_0_2nd_shutdown = if recv_count > 0 {
1045                 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1046                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
1047                 node_0_2nd_shutdown
1048         } else {
1049                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1050                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
1051                 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
1052         };
1053         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown);
1054
1055         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1056         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1057
1058         assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
1059         check_added_monitors!(nodes[2], 1);
1060         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1061         assert!(updates.update_add_htlcs.is_empty());
1062         assert!(updates.update_fail_htlcs.is_empty());
1063         assert!(updates.update_fail_malformed_htlcs.is_empty());
1064         assert!(updates.update_fee.is_none());
1065         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
1066         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
1067         check_added_monitors!(nodes[1], 1);
1068         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1069         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
1070
1071         assert!(updates_2.update_add_htlcs.is_empty());
1072         assert!(updates_2.update_fail_htlcs.is_empty());
1073         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
1074         assert!(updates_2.update_fee.is_none());
1075         assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
1076         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
1077         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
1078
1079         let events = nodes[0].node.get_and_clear_pending_events();
1080         assert_eq!(events.len(), 1);
1081         match events[0] {
1082                 Event::PaymentSent { ref payment_preimage } => {
1083                         assert_eq!(our_payment_preimage, *payment_preimage);
1084                 },
1085                 _ => panic!("Unexpected event"),
1086         }
1087
1088         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1089         if recv_count > 0 {
1090                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
1091                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1092                 assert!(node_1_closing_signed.is_some());
1093         }
1094
1095         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1096         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1097
1098         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1099         let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1100         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1101         if recv_count == 0 {
1102                 // If all closing_signeds weren't delivered we can just resume where we left off...
1103                 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1104
1105                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish);
1106                 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1107                 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
1108
1109                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1110                 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1111                 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
1112
1113                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown);
1114                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1115
1116                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown);
1117                 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1118                 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
1119
1120                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed);
1121                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1122                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
1123                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1124                 assert!(node_0_none.is_none());
1125         } else {
1126                 // If one node, however, received + responded with an identical closing_signed we end
1127                 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
1128                 // There isn't really anything better we can do simply, but in the future we might
1129                 // explore storing a set of recently-closed channels that got disconnected during
1130                 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
1131                 // give our counterparty enough time to (potentially) broadcast a cooperative closing
1132                 // transaction.
1133                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1134
1135                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1136                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1137                 assert_eq!(msg_events.len(), 1);
1138                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
1139                         match action {
1140                                 &ErrorAction::SendErrorMessage { ref msg } => {
1141                                         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
1142                                         assert_eq!(msg.channel_id, chan_1.2);
1143                                 },
1144                                 _ => panic!("Unexpected event!"),
1145                         }
1146                 } else { panic!("Needed SendErrorMessage close"); }
1147
1148                 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
1149                 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
1150                 // closing_signed so we do it ourselves
1151                 check_closed_broadcast!(nodes[0], false);
1152                 check_added_monitors!(nodes[0], 1);
1153         }
1154
1155         assert!(nodes[0].node.list_channels().is_empty());
1156
1157         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1158         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1159         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1160         assert!(nodes[1].node.list_channels().is_empty());
1161         assert!(nodes[2].node.list_channels().is_empty());
1162 }
1163
1164 #[test]
1165 fn test_shutdown_rebroadcast() {
1166         do_test_shutdown_rebroadcast(0);
1167         do_test_shutdown_rebroadcast(1);
1168         do_test_shutdown_rebroadcast(2);
1169 }
1170
1171 #[test]
1172 fn fake_network_test() {
1173         // Simple test which builds a network of ChannelManagers, connects them to each other, and
1174         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
1175         let chanmon_cfgs = create_chanmon_cfgs(4);
1176         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1177         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1178         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1179
1180         // Create some initial channels
1181         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1182         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1183         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1184
1185         // Rebalance the network a bit by relaying one payment through all the channels...
1186         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
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
1191         // Send some more payments
1192         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000, 1_000_000);
1193         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000, 1_000_000);
1194         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000, 1_000_000);
1195
1196         // Test failure packets
1197         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1198         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1199
1200         // Add a new channel that skips 3
1201         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1202
1203         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000, 1_000_000);
1204         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000, 1_000_000);
1205         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_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
1211         // Do some rebalance loop payments, simultaneously
1212         let mut hops = Vec::with_capacity(3);
1213         hops.push(RouteHop {
1214                 pubkey: nodes[2].node.get_our_node_id(),
1215                 node_features: NodeFeatures::empty(),
1216                 short_channel_id: chan_2.0.contents.short_channel_id,
1217                 channel_features: ChannelFeatures::empty(),
1218                 fee_msat: 0,
1219                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1220         });
1221         hops.push(RouteHop {
1222                 pubkey: nodes[3].node.get_our_node_id(),
1223                 node_features: NodeFeatures::empty(),
1224                 short_channel_id: chan_3.0.contents.short_channel_id,
1225                 channel_features: ChannelFeatures::empty(),
1226                 fee_msat: 0,
1227                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1228         });
1229         hops.push(RouteHop {
1230                 pubkey: nodes[1].node.get_our_node_id(),
1231                 node_features: NodeFeatures::empty(),
1232                 short_channel_id: chan_4.0.contents.short_channel_id,
1233                 channel_features: ChannelFeatures::empty(),
1234                 fee_msat: 1000000,
1235                 cltv_expiry_delta: TEST_FINAL_CLTV,
1236         });
1237         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;
1238         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;
1239         let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1240
1241         let mut hops = Vec::with_capacity(3);
1242         hops.push(RouteHop {
1243                 pubkey: nodes[3].node.get_our_node_id(),
1244                 node_features: NodeFeatures::empty(),
1245                 short_channel_id: chan_4.0.contents.short_channel_id,
1246                 channel_features: ChannelFeatures::empty(),
1247                 fee_msat: 0,
1248                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1249         });
1250         hops.push(RouteHop {
1251                 pubkey: nodes[2].node.get_our_node_id(),
1252                 node_features: NodeFeatures::empty(),
1253                 short_channel_id: chan_3.0.contents.short_channel_id,
1254                 channel_features: ChannelFeatures::empty(),
1255                 fee_msat: 0,
1256                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1257         });
1258         hops.push(RouteHop {
1259                 pubkey: nodes[1].node.get_our_node_id(),
1260                 node_features: NodeFeatures::empty(),
1261                 short_channel_id: chan_2.0.contents.short_channel_id,
1262                 channel_features: ChannelFeatures::empty(),
1263                 fee_msat: 1000000,
1264                 cltv_expiry_delta: TEST_FINAL_CLTV,
1265         });
1266         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;
1267         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;
1268         let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1269
1270         // Claim the rebalances...
1271         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1272         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1, 1_000_000);
1273
1274         // Add a duplicate new channel from 2 to 4
1275         let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1276
1277         // Send some payments across both channels
1278         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1279         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1280         let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1281
1282
1283         route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1284         let events = nodes[0].node.get_and_clear_pending_msg_events();
1285         assert_eq!(events.len(), 0);
1286         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);
1287
1288         //TODO: Test that routes work again here as we've been notified that the channel is full
1289
1290         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3, 3_000_000);
1291         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4, 3_000_000);
1292         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5, 3_000_000);
1293
1294         // Close down the channels...
1295         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1296         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1297         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1298         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1299         close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1300 }
1301
1302 #[test]
1303 fn holding_cell_htlc_counting() {
1304         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1305         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1306         // commitment dance rounds.
1307         let chanmon_cfgs = create_chanmon_cfgs(3);
1308         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1309         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1310         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1311         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1312         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1313         let logger = test_utils::TestLogger::new();
1314
1315         let mut payments = Vec::new();
1316         for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1317                 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1318                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1319                 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();
1320                 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
1321                 payments.push((payment_preimage, payment_hash));
1322         }
1323         check_added_monitors!(nodes[1], 1);
1324
1325         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1326         assert_eq!(events.len(), 1);
1327         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1328         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1329
1330         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1331         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1332         // another HTLC.
1333         let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
1334         {
1335                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1336                 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();
1337                 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &None), true, APIError::ChannelUnavailable { ref err },
1338                         assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1339                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1340                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1341         }
1342
1343         // This should also be true if we try to forward a payment.
1344         let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
1345         {
1346                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1347                 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();
1348                 nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
1349                 check_added_monitors!(nodes[0], 1);
1350         }
1351
1352         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1353         assert_eq!(events.len(), 1);
1354         let payment_event = SendEvent::from_event(events.pop().unwrap());
1355         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1356
1357         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1358         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1359         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1360         // fails), the second will process the resulting failure and fail the HTLC backward.
1361         expect_pending_htlcs_forwardable!(nodes[1]);
1362         expect_pending_htlcs_forwardable!(nodes[1]);
1363         check_added_monitors!(nodes[1], 1);
1364
1365         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1366         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1367         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1368
1369         let events = nodes[0].node.get_and_clear_pending_msg_events();
1370         assert_eq!(events.len(), 1);
1371         match events[0] {
1372                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
1373                         assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
1374                 },
1375                 _ => panic!("Unexpected event"),
1376         }
1377
1378         expect_payment_failed!(nodes[0], payment_hash_2, false);
1379
1380         // Now forward all the pending HTLCs and claim them back
1381         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1382         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1383         check_added_monitors!(nodes[2], 1);
1384
1385         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1386         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1387         check_added_monitors!(nodes[1], 1);
1388         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1389
1390         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1391         check_added_monitors!(nodes[1], 1);
1392         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1393
1394         for ref update in as_updates.update_add_htlcs.iter() {
1395                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1396         }
1397         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1398         check_added_monitors!(nodes[2], 1);
1399         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1400         check_added_monitors!(nodes[2], 1);
1401         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1402
1403         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1404         check_added_monitors!(nodes[1], 1);
1405         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1406         check_added_monitors!(nodes[1], 1);
1407         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1408
1409         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1410         check_added_monitors!(nodes[2], 1);
1411
1412         expect_pending_htlcs_forwardable!(nodes[2]);
1413
1414         let events = nodes[2].node.get_and_clear_pending_events();
1415         assert_eq!(events.len(), payments.len());
1416         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1417                 match event {
1418                         &Event::PaymentReceived { ref payment_hash, .. } => {
1419                                 assert_eq!(*payment_hash, *hash);
1420                         },
1421                         _ => panic!("Unexpected event"),
1422                 };
1423         }
1424
1425         for (preimage, _) in payments.drain(..) {
1426                 claim_payment(&nodes[1], &[&nodes[2]], preimage, 100_000);
1427         }
1428
1429         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000, 1_000_000);
1430 }
1431
1432 #[test]
1433 fn duplicate_htlc_test() {
1434         // Test that we accept duplicate payment_hash HTLCs across the network and that
1435         // claiming/failing them are all separate and don't affect each other
1436         let chanmon_cfgs = create_chanmon_cfgs(6);
1437         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1438         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1439         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1440
1441         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1442         create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1443         create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1444         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1445         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1446         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1447
1448         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1449
1450         *nodes[0].network_payment_count.borrow_mut() -= 1;
1451         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1452
1453         *nodes[0].network_payment_count.borrow_mut() -= 1;
1454         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1455
1456         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage, 1_000_000);
1457         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1458         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage, 1_000_000);
1459 }
1460
1461 #[test]
1462 fn test_duplicate_htlc_different_direction_onchain() {
1463         // Test that ChannelMonitor doesn't generate 2 preimage txn
1464         // when we have 2 HTLCs with same preimage that go across a node
1465         // in opposite directions.
1466         let chanmon_cfgs = create_chanmon_cfgs(2);
1467         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1468         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1469         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1470
1471         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1472         let logger = test_utils::TestLogger::new();
1473
1474         // balancing
1475         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
1476
1477         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1478
1479         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1480         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();
1481         send_along_route_with_hash(&nodes[1], route, &vec!(&nodes[0])[..], 800_000, payment_hash);
1482
1483         // Provide preimage to node 0 by claiming payment
1484         nodes[0].node.claim_funds(payment_preimage, &None, 800_000);
1485         check_added_monitors!(nodes[0], 1);
1486
1487         // Broadcast node 1 commitment txn
1488         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1489
1490         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1491         let mut has_both_htlcs = 0; // check htlcs match ones committed
1492         for outp in remote_txn[0].output.iter() {
1493                 if outp.value == 800_000 / 1000 {
1494                         has_both_htlcs += 1;
1495                 } else if outp.value == 900_000 / 1000 {
1496                         has_both_htlcs += 1;
1497                 }
1498         }
1499         assert_eq!(has_both_htlcs, 2);
1500
1501         let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1502         connect_block(&nodes[0], &Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
1503         check_added_monitors!(nodes[0], 1);
1504
1505         // Check we only broadcast 1 timeout tx
1506         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1507         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()) };
1508         assert_eq!(claim_txn.len(), 5);
1509         check_spends!(claim_txn[2], chan_1.3);
1510         check_spends!(claim_txn[3], claim_txn[2]);
1511         assert_eq!(htlc_pair.0.input.len(), 1);
1512         assert_eq!(htlc_pair.0.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1513         check_spends!(htlc_pair.0, remote_txn[0]);
1514         assert_eq!(htlc_pair.1.input.len(), 1);
1515         assert_eq!(htlc_pair.1.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1516         check_spends!(htlc_pair.1, remote_txn[0]);
1517
1518         let events = nodes[0].node.get_and_clear_pending_msg_events();
1519         assert_eq!(events.len(), 2);
1520         for e in events {
1521                 match e {
1522                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1523                         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, .. } } => {
1524                                 assert!(update_add_htlcs.is_empty());
1525                                 assert!(update_fail_htlcs.is_empty());
1526                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1527                                 assert!(update_fail_malformed_htlcs.is_empty());
1528                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1529                         },
1530                         _ => panic!("Unexpected event"),
1531                 }
1532         }
1533 }
1534
1535 #[test]
1536 fn test_basic_channel_reserve() {
1537         let chanmon_cfgs = create_chanmon_cfgs(2);
1538         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1539         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1540         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1541         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1542         let logger = test_utils::TestLogger::new();
1543
1544         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1545         let channel_reserve = chan_stat.channel_reserve_msat;
1546
1547         // The 2* and +1 are for the fee spike reserve.
1548         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
1549         let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1);
1550         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1551         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1552         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();
1553         let err = nodes[0].node.send_payment(&route, our_payment_hash, &None).err().unwrap();
1554         match err {
1555                 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1556                         match &fails[0] {
1557                                 &APIError::ChannelUnavailable{ref err} =>
1558                                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1559                                 _ => panic!("Unexpected error variant"),
1560                         }
1561                 },
1562                 _ => panic!("Unexpected error variant"),
1563         }
1564         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1565         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);
1566
1567         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send, max_can_send);
1568 }
1569
1570 #[test]
1571 fn test_fee_spike_violation_fails_htlc() {
1572         let chanmon_cfgs = create_chanmon_cfgs(2);
1573         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1574         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1575         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1576         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1577         let logger = test_utils::TestLogger::new();
1578
1579         macro_rules! get_route_and_payment_hash {
1580                 ($recv_value: expr) => {{
1581                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1582                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler.network_graph.read().unwrap();
1583                         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();
1584                         (route, payment_hash, payment_preimage)
1585                 }}
1586         };
1587
1588         let (route, payment_hash, _) = get_route_and_payment_hash!(3460001);
1589         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1590         let secp_ctx = Secp256k1::new();
1591         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1592
1593         let cur_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1594
1595         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1596         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &None, cur_height).unwrap();
1597         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1598         let msg = msgs::UpdateAddHTLC {
1599                 channel_id: chan.2,
1600                 htlc_id: 0,
1601                 amount_msat: htlc_msat,
1602                 payment_hash: payment_hash,
1603                 cltv_expiry: htlc_cltv,
1604                 onion_routing_packet: onion_packet,
1605         };
1606
1607         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1608
1609         // Now manually create the commitment_signed message corresponding to the update_add
1610         // nodes[0] just sent. In the code for construction of this message, "local" refers
1611         // to the sender of the message, and "remote" refers to the receiver.
1612
1613         let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1614
1615         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1616
1617         // Get the EnforcingChannelKeys for each channel, which will be used to (1) get the keys
1618         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1619         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point) = {
1620                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1621                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1622                 let chan_keys = local_chan.get_keys();
1623                 let pubkeys = chan_keys.pubkeys();
1624                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1625                  chan_keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1626                  chan_keys.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx))
1627         };
1628         let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point) = {
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,
1634                  chan_keys.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx))
1635         };
1636
1637         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1638         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1639                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1640
1641         // Build the remote commitment transaction so we can sign it, and then later use the
1642         // signature for the commitment_signed message.
1643         let local_chan_balance = 1313;
1644
1645         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1646                 offered: false,
1647                 amount_msat: 3460001,
1648                 cltv_expiry: htlc_cltv,
1649                 payment_hash,
1650                 transaction_output_index: Some(1),
1651         };
1652
1653         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1654
1655         let res = {
1656                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1657                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1658                 let local_chan_keys = local_chan.get_keys();
1659                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1660                         commitment_number,
1661                         95000,
1662                         local_chan_balance,
1663                         commit_tx_keys.clone(),
1664                         feerate_per_kw,
1665                         &mut vec![(accepted_htlc_info, ())],
1666                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1667                 );
1668                 local_chan_keys.sign_counterparty_commitment(&commitment_tx, &secp_ctx).unwrap()
1669         };
1670
1671         let commit_signed_msg = msgs::CommitmentSigned {
1672                 channel_id: chan.2,
1673                 signature: res.0,
1674                 htlc_signatures: res.1
1675         };
1676
1677         // Send the commitment_signed message to the nodes[1].
1678         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1679         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1680
1681         // Send the RAA to nodes[1].
1682         let raa_msg = msgs::RevokeAndACK {
1683                 channel_id: chan.2,
1684                 per_commitment_secret: local_secret,
1685                 next_per_commitment_point: next_local_point
1686         };
1687         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1688
1689         let events = nodes[1].node.get_and_clear_pending_msg_events();
1690         assert_eq!(events.len(), 1);
1691         // Make sure the HTLC failed in the way we expect.
1692         match events[0] {
1693                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1694                         assert_eq!(update_fail_htlcs.len(), 1);
1695                         update_fail_htlcs[0].clone()
1696                 },
1697                 _ => panic!("Unexpected event"),
1698         };
1699         nodes[1].logger.assert_log("lightning::ln::channel".to_string(), "Attempting to fail HTLC due to fee spike buffer violation".to_string(), 1);
1700
1701         check_added_monitors!(nodes[1], 2);
1702 }
1703
1704 #[test]
1705 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1706         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1707         // Set the fee rate for the channel very high, to the point where the fundee
1708         // sending any amount would result in a channel reserve violation. In this test
1709         // we check that we would be prevented from sending an HTLC in this situation.
1710         chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1711         chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1712         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1713         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1714         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1715         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1716         let logger = test_utils::TestLogger::new();
1717
1718         macro_rules! get_route_and_payment_hash {
1719                 ($recv_value: expr) => {{
1720                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1721                         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1722                         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();
1723                         (route, payment_hash, payment_preimage)
1724                 }}
1725         };
1726
1727         let (route, our_payment_hash, _) = get_route_and_payment_hash!(1000);
1728         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1729                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1730         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1731         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);
1732 }
1733
1734 #[test]
1735 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1736         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1737         // Set the fee rate for the channel very high, to the point where the funder
1738         // receiving 1 update_add_htlc would result in them closing the channel due
1739         // to channel reserve violation. This close could also happen if the fee went
1740         // up a more realistic amount, but many HTLCs were outstanding at the time of
1741         // the update_add_htlc.
1742         chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1743         chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1744         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1745         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1746         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1747         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1748         let logger = test_utils::TestLogger::new();
1749
1750         macro_rules! get_route_and_payment_hash {
1751                 ($recv_value: expr) => {{
1752                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1753                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1754                         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();
1755                         (route, payment_hash, payment_preimage)
1756                 }}
1757         };
1758
1759         let (route, payment_hash, _) = get_route_and_payment_hash!(1000);
1760         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1761         let secp_ctx = Secp256k1::new();
1762         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1763         let cur_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1764         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1765         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 1000, &None, cur_height).unwrap();
1766         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1767         let msg = msgs::UpdateAddHTLC {
1768                 channel_id: chan.2,
1769                 htlc_id: 1,
1770                 amount_msat: htlc_msat + 1,
1771                 payment_hash: payment_hash,
1772                 cltv_expiry: htlc_cltv,
1773                 onion_routing_packet: onion_packet,
1774         };
1775
1776         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1777         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1778         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);
1779         assert_eq!(nodes[0].node.list_channels().len(), 0);
1780         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1781         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1782         check_added_monitors!(nodes[0], 1);
1783 }
1784
1785 #[test]
1786 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1787         let chanmon_cfgs = create_chanmon_cfgs(3);
1788         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1789         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1790         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1791         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1792         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1793         let logger = test_utils::TestLogger::new();
1794
1795         macro_rules! get_route_and_payment_hash {
1796                 ($recv_value: expr) => {{
1797                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1798                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1799                         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();
1800                         (route, payment_hash, payment_preimage)
1801                 }}
1802         };
1803
1804         let feemsat = 239;
1805         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1806         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1807         let feerate = get_feerate!(nodes[0], chan.2);
1808
1809         // Add a 2* and +1 for the fee spike reserve.
1810         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1);
1811         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;
1812         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1813
1814         // Add a pending HTLC.
1815         let (route_1, our_payment_hash_1, _) = get_route_and_payment_hash!(amt_msat_1);
1816         let payment_event_1 = {
1817                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
1818                 check_added_monitors!(nodes[0], 1);
1819
1820                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1821                 assert_eq!(events.len(), 1);
1822                 SendEvent::from_event(events.remove(0))
1823         };
1824         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1825
1826         // Attempt to trigger a channel reserve violation --> payment failure.
1827         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2);
1828         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;
1829         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1830         let (route_2, _, _) = get_route_and_payment_hash!(amt_msat_2);
1831
1832         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1833         let secp_ctx = Secp256k1::new();
1834         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1835         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1836         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1837         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height).unwrap();
1838         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1839         let msg = msgs::UpdateAddHTLC {
1840                 channel_id: chan.2,
1841                 htlc_id: 1,
1842                 amount_msat: htlc_msat + 1,
1843                 payment_hash: our_payment_hash_1,
1844                 cltv_expiry: htlc_cltv,
1845                 onion_routing_packet: onion_packet,
1846         };
1847
1848         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1849         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1850         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1851         assert_eq!(nodes[1].node.list_channels().len(), 1);
1852         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1853         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1854         check_added_monitors!(nodes[1], 1);
1855 }
1856
1857 #[test]
1858 fn test_inbound_outbound_capacity_is_not_zero() {
1859         let chanmon_cfgs = create_chanmon_cfgs(2);
1860         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1861         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1862         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1863         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1864         let channels0 = node_chanmgrs[0].list_channels();
1865         let channels1 = node_chanmgrs[1].list_channels();
1866         assert_eq!(channels0.len(), 1);
1867         assert_eq!(channels1.len(), 1);
1868
1869         assert_eq!(channels0[0].inbound_capacity_msat, 95000000);
1870         assert_eq!(channels1[0].outbound_capacity_msat, 95000000);
1871
1872         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000);
1873         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000);
1874 }
1875
1876 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64) -> u64 {
1877         (COMMITMENT_TX_BASE_WEIGHT + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1878 }
1879
1880 #[test]
1881 fn test_channel_reserve_holding_cell_htlcs() {
1882         let chanmon_cfgs = create_chanmon_cfgs(3);
1883         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1884         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1885         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1886         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1887         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1888         let logger = test_utils::TestLogger::new();
1889
1890         let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1891         let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1892
1893         let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1894         let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1895
1896         macro_rules! get_route_and_payment_hash {
1897                 ($recv_value: expr) => {{
1898                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1899                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1900                         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();
1901                         (route, payment_hash, payment_preimage)
1902                 }}
1903         };
1904
1905         macro_rules! expect_forward {
1906                 ($node: expr) => {{
1907                         let mut events = $node.node.get_and_clear_pending_msg_events();
1908                         assert_eq!(events.len(), 1);
1909                         check_added_monitors!($node, 1);
1910                         let payment_event = SendEvent::from_event(events.remove(0));
1911                         payment_event
1912                 }}
1913         }
1914
1915         let feemsat = 239; // somehow we know?
1916         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1917         let feerate = get_feerate!(nodes[0], chan_1.2);
1918
1919         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1920
1921         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1922         {
1923                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
1924                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1925                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1926                         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)));
1927                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1928                 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);
1929         }
1930
1931         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1932         // nodes[0]'s wealth
1933         loop {
1934                 let amt_msat = recv_value_0 + total_fee_msat;
1935                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1936                 // Also, ensure that each payment has enough to be over the dust limit to
1937                 // ensure it'll be included in each commit tx fee calculation.
1938                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1939                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1940                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1941                         break;
1942                 }
1943                 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0, recv_value_0);
1944
1945                 let (stat01_, stat11_, stat12_, stat22_) = (
1946                         get_channel_value_stat!(nodes[0], chan_1.2),
1947                         get_channel_value_stat!(nodes[1], chan_1.2),
1948                         get_channel_value_stat!(nodes[1], chan_2.2),
1949                         get_channel_value_stat!(nodes[2], chan_2.2),
1950                 );
1951
1952                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1953                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1954                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1955                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1956                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1957         }
1958
1959         // adding pending output.
1960         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1961         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1962         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1963         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1964         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1965         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1966         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1967         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1968         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1969         // policy.
1970         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1);
1971         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1972         let amt_msat_1 = recv_value_1 + total_fee_msat;
1973
1974         let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
1975         let payment_event_1 = {
1976                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
1977                 check_added_monitors!(nodes[0], 1);
1978
1979                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1980                 assert_eq!(events.len(), 1);
1981                 SendEvent::from_event(events.remove(0))
1982         };
1983         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1984
1985         // channel reserve test with htlc pending output > 0
1986         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1987         {
1988                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
1989                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1990                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1991                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1992         }
1993
1994         // split the rest to test holding cell
1995         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1996         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1997         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1998         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1999         {
2000                 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
2001                 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);
2002         }
2003
2004         // now see if they go through on both sides
2005         let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
2006         // but this will stuck in the holding cell
2007         nodes[0].node.send_payment(&route_21, our_payment_hash_21, &None).unwrap();
2008         check_added_monitors!(nodes[0], 0);
2009         let events = nodes[0].node.get_and_clear_pending_events();
2010         assert_eq!(events.len(), 0);
2011
2012         // test with outbound holding cell amount > 0
2013         {
2014                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
2015                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
2016                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
2017                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2018                 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);
2019         }
2020
2021         let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
2022         // this will also stuck in the holding cell
2023         nodes[0].node.send_payment(&route_22, our_payment_hash_22, &None).unwrap();
2024         check_added_monitors!(nodes[0], 0);
2025         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
2026         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2027
2028         // flush the pending htlc
2029         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
2030         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2031         check_added_monitors!(nodes[1], 1);
2032
2033         // the pending htlc should be promoted to committed
2034         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
2035         check_added_monitors!(nodes[0], 1);
2036         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2037
2038         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
2039         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2040         // No commitment_signed so get_event_msg's assert(len == 1) passes
2041         check_added_monitors!(nodes[0], 1);
2042
2043         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
2044         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2045         check_added_monitors!(nodes[1], 1);
2046
2047         expect_pending_htlcs_forwardable!(nodes[1]);
2048
2049         let ref payment_event_11 = expect_forward!(nodes[1]);
2050         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
2051         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
2052
2053         expect_pending_htlcs_forwardable!(nodes[2]);
2054         expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
2055
2056         // flush the htlcs in the holding cell
2057         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
2058         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
2059         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
2060         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
2061         expect_pending_htlcs_forwardable!(nodes[1]);
2062
2063         let ref payment_event_3 = expect_forward!(nodes[1]);
2064         assert_eq!(payment_event_3.msgs.len(), 2);
2065         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
2066         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
2067
2068         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2069         expect_pending_htlcs_forwardable!(nodes[2]);
2070
2071         let events = nodes[2].node.get_and_clear_pending_events();
2072         assert_eq!(events.len(), 2);
2073         match events[0] {
2074                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2075                         assert_eq!(our_payment_hash_21, *payment_hash);
2076                         assert_eq!(*payment_secret, None);
2077                         assert_eq!(recv_value_21, amt);
2078                 },
2079                 _ => panic!("Unexpected event"),
2080         }
2081         match events[1] {
2082                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2083                         assert_eq!(our_payment_hash_22, *payment_hash);
2084                         assert_eq!(None, *payment_secret);
2085                         assert_eq!(recv_value_22, amt);
2086                 },
2087                 _ => panic!("Unexpected event"),
2088         }
2089
2090         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1, recv_value_1);
2091         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21, recv_value_21);
2092         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22, recv_value_22);
2093
2094         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1);
2095         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2096         {
2097                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_3 + 1);
2098                 let err = nodes[0].node.send_payment(&route, our_payment_hash, &None).err().unwrap();
2099                 match err {
2100                         PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
2101                                 match &fails[0] {
2102                                         &APIError::ChannelUnavailable{ref err} =>
2103                                                 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
2104                                         _ => panic!("Unexpected error variant"),
2105                                 }
2106                         },
2107                         _ => panic!("Unexpected error variant"),
2108                 }
2109                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2110                 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);
2111         }
2112
2113         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3, recv_value_3);
2114
2115         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1);
2116         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);
2117         let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2118         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2119         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2120
2121         let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2122         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2123 }
2124
2125 #[test]
2126 fn channel_reserve_in_flight_removes() {
2127         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2128         // can send to its counterparty, but due to update ordering, the other side may not yet have
2129         // considered those HTLCs fully removed.
2130         // This tests that we don't count HTLCs which will not be included in the next remote
2131         // commitment transaction towards the reserve value (as it implies no commitment transaction
2132         // will be generated which violates the remote reserve value).
2133         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2134         // To test this we:
2135         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2136         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2137         //    you only consider the value of the first HTLC, it may not),
2138         //  * start routing a third HTLC from A to B,
2139         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2140         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2141         //  * deliver the first fulfill from B
2142         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2143         //    claim,
2144         //  * deliver A's response CS and RAA.
2145         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2146         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2147         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2148         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2149         let chanmon_cfgs = create_chanmon_cfgs(2);
2150         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2151         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2152         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2153         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2154         let logger = test_utils::TestLogger::new();
2155
2156         let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2157         // Route the first two HTLCs.
2158         let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
2159         let (payment_preimage_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
2160
2161         // Start routing the third HTLC (this is just used to get everyone in the right state).
2162         let (payment_preimage_3, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
2163         let send_1 = {
2164                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
2165                 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();
2166                 nodes[0].node.send_payment(&route, payment_hash_3, &None).unwrap();
2167                 check_added_monitors!(nodes[0], 1);
2168                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2169                 assert_eq!(events.len(), 1);
2170                 SendEvent::from_event(events.remove(0))
2171         };
2172
2173         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2174         // initial fulfill/CS.
2175         assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000));
2176         check_added_monitors!(nodes[1], 1);
2177         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2178
2179         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2180         // remove the second HTLC when we send the HTLC back from B to A.
2181         assert!(nodes[1].node.claim_funds(payment_preimage_2, &None, 20000));
2182         check_added_monitors!(nodes[1], 1);
2183         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2184
2185         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2186         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2187         check_added_monitors!(nodes[0], 1);
2188         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2189         expect_payment_sent!(nodes[0], payment_preimage_1);
2190
2191         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2192         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2193         check_added_monitors!(nodes[1], 1);
2194         // B is already AwaitingRAA, so cant generate a CS here
2195         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2196
2197         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2198         check_added_monitors!(nodes[1], 1);
2199         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2200
2201         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2202         check_added_monitors!(nodes[0], 1);
2203         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2204
2205         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2206         check_added_monitors!(nodes[1], 1);
2207         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2208
2209         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2210         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2211         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2212         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2213         // on-chain as necessary).
2214         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2215         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2216         check_added_monitors!(nodes[0], 1);
2217         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2218         expect_payment_sent!(nodes[0], payment_preimage_2);
2219
2220         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2221         check_added_monitors!(nodes[1], 1);
2222         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2223
2224         expect_pending_htlcs_forwardable!(nodes[1]);
2225         expect_payment_received!(nodes[1], payment_hash_3, 100000);
2226
2227         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2228         // resolve the second HTLC from A's point of view.
2229         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2230         check_added_monitors!(nodes[0], 1);
2231         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2232
2233         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2234         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2235         let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[1]);
2236         let send_2 = {
2237                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
2238                 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();
2239                 nodes[1].node.send_payment(&route, payment_hash_4, &None).unwrap();
2240                 check_added_monitors!(nodes[1], 1);
2241                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2242                 assert_eq!(events.len(), 1);
2243                 SendEvent::from_event(events.remove(0))
2244         };
2245
2246         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2247         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2248         check_added_monitors!(nodes[0], 1);
2249         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2250
2251         // Now just resolve all the outstanding messages/HTLCs for completeness...
2252
2253         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2254         check_added_monitors!(nodes[1], 1);
2255         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2256
2257         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2258         check_added_monitors!(nodes[1], 1);
2259
2260         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2261         check_added_monitors!(nodes[0], 1);
2262         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2263
2264         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2265         check_added_monitors!(nodes[1], 1);
2266         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2267
2268         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2269         check_added_monitors!(nodes[0], 1);
2270
2271         expect_pending_htlcs_forwardable!(nodes[0]);
2272         expect_payment_received!(nodes[0], payment_hash_4, 10000);
2273
2274         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4, 10_000);
2275         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3, 100_000);
2276 }
2277
2278 #[test]
2279 fn channel_monitor_network_test() {
2280         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2281         // tests that ChannelMonitor is able to recover from various states.
2282         let chanmon_cfgs = create_chanmon_cfgs(5);
2283         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2284         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2285         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2286
2287         // Create some initial channels
2288         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2289         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2290         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2291         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2292
2293         // Rebalance the network a bit by relaying one payment through all the channels...
2294         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2295         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2296         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2297         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2298
2299         // Simple case with no pending HTLCs:
2300         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2301         check_added_monitors!(nodes[1], 1);
2302         {
2303                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2304                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2305                 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
2306                 check_added_monitors!(nodes[0], 1);
2307                 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2308         }
2309         get_announce_close_broadcast_events(&nodes, 0, 1);
2310         assert_eq!(nodes[0].node.list_channels().len(), 0);
2311         assert_eq!(nodes[1].node.list_channels().len(), 1);
2312
2313         // One pending HTLC is discarded by the force-close:
2314         let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2315
2316         // Simple case of one pending HTLC to HTLC-Timeout
2317         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2318         check_added_monitors!(nodes[1], 1);
2319         {
2320                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2321                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2322                 connect_block(&nodes[2], &Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
2323                 check_added_monitors!(nodes[2], 1);
2324                 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2325         }
2326         get_announce_close_broadcast_events(&nodes, 1, 2);
2327         assert_eq!(nodes[1].node.list_channels().len(), 0);
2328         assert_eq!(nodes[2].node.list_channels().len(), 1);
2329
2330         macro_rules! claim_funds {
2331                 ($node: expr, $prev_node: expr, $preimage: expr, $amount: expr) => {
2332                         {
2333                                 assert!($node.node.claim_funds($preimage, &None, $amount));
2334                                 check_added_monitors!($node, 1);
2335
2336                                 let events = $node.node.get_and_clear_pending_msg_events();
2337                                 assert_eq!(events.len(), 1);
2338                                 match events[0] {
2339                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2340                                                 assert!(update_add_htlcs.is_empty());
2341                                                 assert!(update_fail_htlcs.is_empty());
2342                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2343                                         },
2344                                         _ => panic!("Unexpected event"),
2345                                 };
2346                         }
2347                 }
2348         }
2349
2350         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2351         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2352         nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2353         check_added_monitors!(nodes[2], 1);
2354         let node2_commitment_txid;
2355         {
2356                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2357                 node2_commitment_txid = node_txn[0].txid();
2358
2359                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2360                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, 3_000_000);
2361
2362                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2363                 connect_block(&nodes[3], &Block { header, txdata: vec![node_txn[0].clone()] }, 1);
2364                 check_added_monitors!(nodes[3], 1);
2365
2366                 check_preimage_claim(&nodes[3], &node_txn);
2367         }
2368         get_announce_close_broadcast_events(&nodes, 2, 3);
2369         assert_eq!(nodes[2].node.list_channels().len(), 0);
2370         assert_eq!(nodes[3].node.list_channels().len(), 1);
2371
2372         { // Cheat and reset nodes[4]'s height to 1
2373                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2374                 connect_block(&nodes[4], &Block { header, txdata: vec![] }, 1);
2375         }
2376
2377         assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
2378         assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
2379         // One pending HTLC to time out:
2380         let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2381         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2382         // buffer space).
2383
2384         let (close_chan_update_1, close_chan_update_2) = {
2385                 let mut block = Block {
2386                         header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2387                         txdata: vec![],
2388                 };
2389                 connect_block(&nodes[3], &block, 2);
2390                 for i in 3..TEST_FINAL_CLTV + 2 + LATENCY_GRACE_PERIOD_BLOCKS + 1 {
2391                         block = Block {
2392                                 header: BlockHeader { version: 0x20000000, prev_blockhash: block.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2393                                 txdata: vec![],
2394                         };
2395                         connect_block(&nodes[3], &block, i);
2396                 }
2397                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2398                 assert_eq!(events.len(), 1);
2399                 let close_chan_update_1 = match events[0] {
2400                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2401                                 msg.clone()
2402                         },
2403                         _ => panic!("Unexpected event"),
2404                 };
2405                 check_added_monitors!(nodes[3], 1);
2406
2407                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2408                 {
2409                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2410                         node_txn.retain(|tx| {
2411                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2412                                         false
2413                                 } else { true }
2414                         });
2415                 }
2416
2417                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2418
2419                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2420                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, 3_000_000);
2421
2422                 block = Block {
2423                         header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2424                         txdata: vec![],
2425                 };
2426
2427                 connect_block(&nodes[4], &block, 2);
2428                 for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
2429                         block = Block {
2430                                 header: BlockHeader { version: 0x20000000, prev_blockhash: block.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2431                                 txdata: vec![],
2432                         };
2433                         connect_block(&nodes[4], &block, i);
2434                 }
2435                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2436                 assert_eq!(events.len(), 1);
2437                 let close_chan_update_2 = match events[0] {
2438                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2439                                 msg.clone()
2440                         },
2441                         _ => panic!("Unexpected event"),
2442                 };
2443                 check_added_monitors!(nodes[4], 1);
2444                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2445
2446                 block = Block {
2447                         header: BlockHeader { version: 0x20000000, prev_blockhash: block.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2448                         txdata: vec![node_txn[0].clone()],
2449                 };
2450                 connect_block(&nodes[4], &block, TEST_FINAL_CLTV - 5);
2451
2452                 check_preimage_claim(&nodes[4], &node_txn);
2453                 (close_chan_update_1, close_chan_update_2)
2454         };
2455         nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2456         nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2457         assert_eq!(nodes[3].node.list_channels().len(), 0);
2458         assert_eq!(nodes[4].node.list_channels().len(), 0);
2459 }
2460
2461 #[test]
2462 fn test_justice_tx() {
2463         // Test justice txn built on revoked HTLC-Success tx, against both sides
2464         let mut alice_config = UserConfig::default();
2465         alice_config.channel_options.announced_channel = true;
2466         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2467         alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2468         let mut bob_config = UserConfig::default();
2469         bob_config.channel_options.announced_channel = true;
2470         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2471         bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2472         let user_cfgs = [Some(alice_config), Some(bob_config)];
2473         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2474         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2475         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2476         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2477         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2478         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2479         // Create some new channels:
2480         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2481
2482         // A pending HTLC which will be revoked:
2483         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2484         // Get the will-be-revoked local txn from nodes[0]
2485         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2486         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2487         assert_eq!(revoked_local_txn[0].input.len(), 1);
2488         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2489         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2490         assert_eq!(revoked_local_txn[1].input.len(), 1);
2491         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2492         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2493         // Revoke the old state
2494         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 3_000_000);
2495
2496         {
2497                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2498                 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2499                 {
2500                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2501                         assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2502                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2503
2504                         check_spends!(node_txn[0], revoked_local_txn[0]);
2505                         node_txn.swap_remove(0);
2506                         node_txn.truncate(1);
2507                 }
2508                 check_added_monitors!(nodes[1], 1);
2509                 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2510
2511                 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2512                 // Verify broadcast of revoked HTLC-timeout
2513                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2514                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2515                 check_added_monitors!(nodes[0], 1);
2516                 // Broadcast revoked HTLC-timeout on node 1
2517                 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2518                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2519         }
2520         get_announce_close_broadcast_events(&nodes, 0, 1);
2521
2522         assert_eq!(nodes[0].node.list_channels().len(), 0);
2523         assert_eq!(nodes[1].node.list_channels().len(), 0);
2524
2525         // We test justice_tx build by A on B's revoked HTLC-Success tx
2526         // Create some new channels:
2527         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2528         {
2529                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2530                 node_txn.clear();
2531         }
2532
2533         // A pending HTLC which will be revoked:
2534         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2535         // Get the will-be-revoked local txn from B
2536         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2537         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2538         assert_eq!(revoked_local_txn[0].input.len(), 1);
2539         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2540         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2541         // Revoke the old state
2542         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4, 3_000_000);
2543         {
2544                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2545                 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2546                 {
2547                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2548                         assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2549                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2550
2551                         check_spends!(node_txn[0], revoked_local_txn[0]);
2552                         node_txn.swap_remove(0);
2553                 }
2554                 check_added_monitors!(nodes[0], 1);
2555                 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2556
2557                 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2558                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2559                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2560                 check_added_monitors!(nodes[1], 1);
2561                 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2562                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2563         }
2564         get_announce_close_broadcast_events(&nodes, 0, 1);
2565         assert_eq!(nodes[0].node.list_channels().len(), 0);
2566         assert_eq!(nodes[1].node.list_channels().len(), 0);
2567 }
2568
2569 #[test]
2570 fn revoked_output_claim() {
2571         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2572         // transaction is broadcast by its counterparty
2573         let chanmon_cfgs = create_chanmon_cfgs(2);
2574         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2575         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2576         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2577         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2578         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2579         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2580         assert_eq!(revoked_local_txn.len(), 1);
2581         // Only output is the full channel value back to nodes[0]:
2582         assert_eq!(revoked_local_txn[0].output.len(), 1);
2583         // Send a payment through, updating everyone's latest commitment txn
2584         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000, 5_000_000);
2585
2586         // Inform nodes[1] that nodes[0] broadcast a stale tx
2587         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2588         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2589         check_added_monitors!(nodes[1], 1);
2590         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2591         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2592
2593         check_spends!(node_txn[0], revoked_local_txn[0]);
2594         check_spends!(node_txn[1], chan_1.3);
2595
2596         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2597         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2598         get_announce_close_broadcast_events(&nodes, 0, 1);
2599         check_added_monitors!(nodes[0], 1)
2600 }
2601
2602 #[test]
2603 fn claim_htlc_outputs_shared_tx() {
2604         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2605         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2606         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2607         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2608         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2609         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2610
2611         // Create some new channel:
2612         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2613
2614         // Rebalance the network to generate htlc in the two directions
2615         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2616         // 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
2617         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2618         let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2619
2620         // Get the will-be-revoked local txn from node[0]
2621         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2622         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2623         assert_eq!(revoked_local_txn[0].input.len(), 1);
2624         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2625         assert_eq!(revoked_local_txn[1].input.len(), 1);
2626         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2627         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2628         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2629
2630         //Revoke the old state
2631         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2632
2633         {
2634                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2635                 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2636                 check_added_monitors!(nodes[0], 1);
2637                 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2638                 check_added_monitors!(nodes[1], 1);
2639                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
2640                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2641
2642                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2643                 assert_eq!(node_txn.len(), 3); // ChannelMonitor: penalty tx, ChannelManager: local commitment + HTLC-timeout
2644
2645                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2646                 check_spends!(node_txn[0], revoked_local_txn[0]);
2647
2648                 let mut witness_lens = BTreeSet::new();
2649                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2650                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2651                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2652                 assert_eq!(witness_lens.len(), 3);
2653                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2654                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2655                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2656
2657                 // Next nodes[1] broadcasts its current local tx state:
2658                 assert_eq!(node_txn[1].input.len(), 1);
2659                 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2660
2661                 assert_eq!(node_txn[2].input.len(), 1);
2662                 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
2663                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2664                 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
2665                 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
2666                 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
2667         }
2668         get_announce_close_broadcast_events(&nodes, 0, 1);
2669         assert_eq!(nodes[0].node.list_channels().len(), 0);
2670         assert_eq!(nodes[1].node.list_channels().len(), 0);
2671 }
2672
2673 #[test]
2674 fn claim_htlc_outputs_single_tx() {
2675         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2676         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2677         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2678         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2679         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2680         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2681
2682         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2683
2684         // Rebalance the network to generate htlc in the two directions
2685         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2686         // 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
2687         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2688         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2689         let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2690
2691         // Get the will-be-revoked local txn from node[0]
2692         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2693
2694         //Revoke the old state
2695         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2696
2697         {
2698                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2699                 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2700                 check_added_monitors!(nodes[0], 1);
2701                 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2702                 check_added_monitors!(nodes[1], 1);
2703                 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
2704
2705                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 200, true, header.block_hash());
2706                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2707
2708                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2709                 assert_eq!(node_txn.len(), 9);
2710                 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2711                 // ChannelManager: local commmitment + local HTLC-timeout (2)
2712                 // 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)
2713                 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2714
2715                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2716                 assert_eq!(node_txn[2].input.len(), 1);
2717                 check_spends!(node_txn[2], chan_1.3);
2718                 assert_eq!(node_txn[3].input.len(), 1);
2719                 let witness_script = node_txn[3].input[0].witness.last().unwrap();
2720                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2721                 check_spends!(node_txn[3], node_txn[2]);
2722
2723                 // Justice transactions are indices 1-2-4
2724                 assert_eq!(node_txn[0].input.len(), 1);
2725                 assert_eq!(node_txn[1].input.len(), 1);
2726                 assert_eq!(node_txn[4].input.len(), 1);
2727
2728                 check_spends!(node_txn[0], revoked_local_txn[0]);
2729                 check_spends!(node_txn[1], revoked_local_txn[0]);
2730                 check_spends!(node_txn[4], revoked_local_txn[0]);
2731
2732                 let mut witness_lens = BTreeSet::new();
2733                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2734                 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2735                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2736                 assert_eq!(witness_lens.len(), 3);
2737                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2738                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2739                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2740         }
2741         get_announce_close_broadcast_events(&nodes, 0, 1);
2742         assert_eq!(nodes[0].node.list_channels().len(), 0);
2743         assert_eq!(nodes[1].node.list_channels().len(), 0);
2744 }
2745
2746 #[test]
2747 fn test_htlc_on_chain_success() {
2748         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2749         // the preimage backward accordingly. So here we test that ChannelManager is
2750         // broadcasting the right event to other nodes in payment path.
2751         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2752         // A --------------------> B ----------------------> C (preimage)
2753         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2754         // commitment transaction was broadcast.
2755         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2756         // towards B.
2757         // B should be able to claim via preimage if A then broadcasts its local tx.
2758         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2759         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2760         // PaymentSent event).
2761
2762         let chanmon_cfgs = create_chanmon_cfgs(3);
2763         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2764         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2765         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2766
2767         // Create some initial channels
2768         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2769         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2770
2771         // Rebalance the network a bit by relaying one payment through all the channels...
2772         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2773         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2774
2775         let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2776         let (our_payment_preimage_2, _payment_hash_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2777         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2778
2779         // Broadcast legit commitment tx from C on B's chain
2780         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2781         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2782         assert_eq!(commitment_tx.len(), 1);
2783         check_spends!(commitment_tx[0], chan_2.3);
2784         nodes[2].node.claim_funds(our_payment_preimage, &None, 3_000_000);
2785         nodes[2].node.claim_funds(our_payment_preimage_2, &None, 3_000_000);
2786         check_added_monitors!(nodes[2], 2);
2787         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2788         assert!(updates.update_add_htlcs.is_empty());
2789         assert!(updates.update_fail_htlcs.is_empty());
2790         assert!(updates.update_fail_malformed_htlcs.is_empty());
2791         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2792
2793         connect_block(&nodes[2], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2794         check_closed_broadcast!(nodes[2], false);
2795         check_added_monitors!(nodes[2], 1);
2796         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)
2797         assert_eq!(node_txn.len(), 5);
2798         assert_eq!(node_txn[0], node_txn[3]);
2799         assert_eq!(node_txn[1], node_txn[4]);
2800         assert_eq!(node_txn[2], commitment_tx[0]);
2801         check_spends!(node_txn[0], commitment_tx[0]);
2802         check_spends!(node_txn[1], commitment_tx[0]);
2803         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2804         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2805         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2806         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2807         assert_eq!(node_txn[0].lock_time, 0);
2808         assert_eq!(node_txn[1].lock_time, 0);
2809
2810         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2811         connect_block(&nodes[1], &Block { header, txdata: node_txn}, 1);
2812         {
2813                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2814                 assert_eq!(added_monitors.len(), 1);
2815                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2816                 added_monitors.clear();
2817         }
2818         let events = nodes[1].node.get_and_clear_pending_msg_events();
2819         {
2820                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2821                 assert_eq!(added_monitors.len(), 2);
2822                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2823                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2824                 added_monitors.clear();
2825         }
2826         assert_eq!(events.len(), 2);
2827         match events[0] {
2828                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2829                 _ => panic!("Unexpected event"),
2830         }
2831         match events[1] {
2832                 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, .. } } => {
2833                         assert!(update_add_htlcs.is_empty());
2834                         assert!(update_fail_htlcs.is_empty());
2835                         assert_eq!(update_fulfill_htlcs.len(), 1);
2836                         assert!(update_fail_malformed_htlcs.is_empty());
2837                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2838                 },
2839                 _ => panic!("Unexpected event"),
2840         };
2841         macro_rules! check_tx_local_broadcast {
2842                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2843                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2844                         assert_eq!(node_txn.len(), 5);
2845                         // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2846                         // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2847                         check_spends!(node_txn[0], $commitment_tx);
2848                         check_spends!(node_txn[1], $commitment_tx);
2849                         assert_ne!(node_txn[0].lock_time, 0);
2850                         assert_ne!(node_txn[1].lock_time, 0);
2851                         if $htlc_offered {
2852                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2853                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2854                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2855                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2856                         } else {
2857                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2858                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2859                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2860                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2861                         }
2862                         check_spends!(node_txn[2], $chan_tx);
2863                         check_spends!(node_txn[3], node_txn[2]);
2864                         check_spends!(node_txn[4], node_txn[2]);
2865                         assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), 71);
2866                         assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2867                         assert_eq!(node_txn[4].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2868                         assert!(node_txn[3].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2869                         assert!(node_txn[4].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2870                         assert_ne!(node_txn[3].lock_time, 0);
2871                         assert_ne!(node_txn[4].lock_time, 0);
2872                         node_txn.clear();
2873                 } }
2874         }
2875         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2876         // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2877         // timeout-claim of the output that nodes[2] just claimed via success.
2878         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2879
2880         // Broadcast legit commitment tx from A on B's chain
2881         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2882         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2883         check_spends!(commitment_tx[0], chan_1.3);
2884         connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2885         check_closed_broadcast!(nodes[1], false);
2886         check_added_monitors!(nodes[1], 1);
2887         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 1 (HTLC-Success)
2888         assert_eq!(node_txn.len(), 4);
2889         check_spends!(node_txn[0], commitment_tx[0]);
2890         assert_eq!(node_txn[0].input.len(), 2);
2891         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2892         assert_eq!(node_txn[0].input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2893         assert_eq!(node_txn[0].lock_time, 0);
2894         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2895         check_spends!(node_txn[1], chan_1.3);
2896         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
2897         check_spends!(node_txn[2], node_txn[1]);
2898         check_spends!(node_txn[3], node_txn[1]);
2899         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2900         // we already checked the same situation with A.
2901
2902         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2903         connect_block(&nodes[0], &Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
2904         check_closed_broadcast!(nodes[0], false);
2905         check_added_monitors!(nodes[0], 1);
2906         let events = nodes[0].node.get_and_clear_pending_events();
2907         assert_eq!(events.len(), 2);
2908         let mut first_claimed = false;
2909         for event in events {
2910                 match event {
2911                         Event::PaymentSent { payment_preimage } => {
2912                                 if payment_preimage == our_payment_preimage {
2913                                         assert!(!first_claimed);
2914                                         first_claimed = true;
2915                                 } else {
2916                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2917                                 }
2918                         },
2919                         _ => panic!("Unexpected event"),
2920                 }
2921         }
2922         check_tx_local_broadcast!(nodes[0], true, commitment_tx[0], chan_1.3);
2923 }
2924
2925 #[test]
2926 fn test_htlc_on_chain_timeout() {
2927         // Test that in case of a unilateral close onchain, we detect the state of output and
2928         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2929         // broadcasting the right event to other nodes in payment path.
2930         // A ------------------> B ----------------------> C (timeout)
2931         //    B's commitment tx                 C's commitment tx
2932         //            \                                  \
2933         //         B's HTLC timeout tx               B's timeout tx
2934
2935         let chanmon_cfgs = create_chanmon_cfgs(3);
2936         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2937         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2938         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2939
2940         // Create some intial channels
2941         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2942         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2943
2944         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2945         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2946         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2947
2948         let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2949         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2950
2951         // Broadcast legit commitment tx from C on B's chain
2952         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2953         check_spends!(commitment_tx[0], chan_2.3);
2954         nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
2955         check_added_monitors!(nodes[2], 0);
2956         expect_pending_htlcs_forwardable!(nodes[2]);
2957         check_added_monitors!(nodes[2], 1);
2958
2959         let events = nodes[2].node.get_and_clear_pending_msg_events();
2960         assert_eq!(events.len(), 1);
2961         match events[0] {
2962                 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, .. } } => {
2963                         assert!(update_add_htlcs.is_empty());
2964                         assert!(!update_fail_htlcs.is_empty());
2965                         assert!(update_fulfill_htlcs.is_empty());
2966                         assert!(update_fail_malformed_htlcs.is_empty());
2967                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2968                 },
2969                 _ => panic!("Unexpected event"),
2970         };
2971         connect_block(&nodes[2], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2972         check_closed_broadcast!(nodes[2], false);
2973         check_added_monitors!(nodes[2], 1);
2974         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2975         assert_eq!(node_txn.len(), 1);
2976         check_spends!(node_txn[0], chan_2.3);
2977         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2978
2979         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2980         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2981         connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
2982         let timeout_tx;
2983         {
2984                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2985                 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2986                 assert_eq!(node_txn[1], node_txn[3]);
2987                 assert_eq!(node_txn[2], node_txn[4]);
2988
2989                 check_spends!(node_txn[0], commitment_tx[0]);
2990                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2991
2992                 check_spends!(node_txn[1], chan_2.3);
2993                 check_spends!(node_txn[2], node_txn[1]);
2994                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
2995                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2996
2997                 timeout_tx = node_txn[0].clone();
2998                 node_txn.clear();
2999         }
3000
3001         connect_block(&nodes[1], &Block { header, txdata: vec![timeout_tx]}, 1);
3002         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
3003         check_added_monitors!(nodes[1], 1);
3004         check_closed_broadcast!(nodes[1], false);
3005
3006         expect_pending_htlcs_forwardable!(nodes[1]);
3007         check_added_monitors!(nodes[1], 1);
3008         let events = nodes[1].node.get_and_clear_pending_msg_events();
3009         assert_eq!(events.len(), 1);
3010         match events[0] {
3011                 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, .. } } => {
3012                         assert!(update_add_htlcs.is_empty());
3013                         assert!(!update_fail_htlcs.is_empty());
3014                         assert!(update_fulfill_htlcs.is_empty());
3015                         assert!(update_fail_malformed_htlcs.is_empty());
3016                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3017                 },
3018                 _ => panic!("Unexpected event"),
3019         };
3020         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
3021         assert_eq!(node_txn.len(), 0);
3022
3023         // Broadcast legit commitment tx from B on A's chain
3024         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3025         check_spends!(commitment_tx[0], chan_1.3);
3026
3027         connect_block(&nodes[0], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
3028         check_closed_broadcast!(nodes[0], false);
3029         check_added_monitors!(nodes[0], 1);
3030         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 1 timeout tx
3031         assert_eq!(node_txn.len(), 3);
3032         check_spends!(node_txn[0], commitment_tx[0]);
3033         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3034         check_spends!(node_txn[1], chan_1.3);
3035         check_spends!(node_txn[2], node_txn[1]);
3036         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
3037         assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3038 }
3039
3040 #[test]
3041 fn test_simple_commitment_revoked_fail_backward() {
3042         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3043         // and fail backward accordingly.
3044
3045         let chanmon_cfgs = create_chanmon_cfgs(3);
3046         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3047         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3048         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3049
3050         // Create some initial channels
3051         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3052         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3053
3054         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3055         // Get the will-be-revoked local txn from nodes[2]
3056         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3057         // Revoke the old state
3058         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, 3_000_000);
3059
3060         let (_, payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3061
3062         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
3063         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3064         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
3065         check_added_monitors!(nodes[1], 1);
3066         check_closed_broadcast!(nodes[1], false);
3067
3068         expect_pending_htlcs_forwardable!(nodes[1]);
3069         check_added_monitors!(nodes[1], 1);
3070         let events = nodes[1].node.get_and_clear_pending_msg_events();
3071         assert_eq!(events.len(), 1);
3072         match events[0] {
3073                 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, .. } } => {
3074                         assert!(update_add_htlcs.is_empty());
3075                         assert_eq!(update_fail_htlcs.len(), 1);
3076                         assert!(update_fulfill_htlcs.is_empty());
3077                         assert!(update_fail_malformed_htlcs.is_empty());
3078                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3079
3080                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3081                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3082
3083                         let events = nodes[0].node.get_and_clear_pending_msg_events();
3084                         assert_eq!(events.len(), 1);
3085                         match events[0] {
3086                                 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3087                                 _ => panic!("Unexpected event"),
3088                         }
3089                         expect_payment_failed!(nodes[0], payment_hash, false);
3090                 },
3091                 _ => panic!("Unexpected event"),
3092         }
3093 }
3094
3095 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3096         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3097         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3098         // commitment transaction anymore.
3099         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3100         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3101         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3102         // technically disallowed and we should probably handle it reasonably.
3103         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3104         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3105         // transactions:
3106         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3107         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3108         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3109         //   and once they revoke the previous commitment transaction (allowing us to send a new
3110         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3111         let chanmon_cfgs = create_chanmon_cfgs(3);
3112         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3113         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3114         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3115
3116         // Create some initial channels
3117         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3118         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3119
3120         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3121         // Get the will-be-revoked local txn from nodes[2]
3122         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3123         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3124         // Revoke the old state
3125         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, if no_to_remote { 10_000 } else { 3_000_000});
3126
3127         let value = if use_dust {
3128                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3129                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3130                 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3131         } else { 3000000 };
3132
3133         let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3134         let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3135         let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3136
3137         assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, &None));
3138         expect_pending_htlcs_forwardable!(nodes[2]);
3139         check_added_monitors!(nodes[2], 1);
3140         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3141         assert!(updates.update_add_htlcs.is_empty());
3142         assert!(updates.update_fulfill_htlcs.is_empty());
3143         assert!(updates.update_fail_malformed_htlcs.is_empty());
3144         assert_eq!(updates.update_fail_htlcs.len(), 1);
3145         assert!(updates.update_fee.is_none());
3146         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3147         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3148         // Drop the last RAA from 3 -> 2
3149
3150         assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, &None));
3151         expect_pending_htlcs_forwardable!(nodes[2]);
3152         check_added_monitors!(nodes[2], 1);
3153         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3154         assert!(updates.update_add_htlcs.is_empty());
3155         assert!(updates.update_fulfill_htlcs.is_empty());
3156         assert!(updates.update_fail_malformed_htlcs.is_empty());
3157         assert_eq!(updates.update_fail_htlcs.len(), 1);
3158         assert!(updates.update_fee.is_none());
3159         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3160         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3161         check_added_monitors!(nodes[1], 1);
3162         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3163         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3164         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3165         check_added_monitors!(nodes[2], 1);
3166
3167         assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, &None));
3168         expect_pending_htlcs_forwardable!(nodes[2]);
3169         check_added_monitors!(nodes[2], 1);
3170         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3171         assert!(updates.update_add_htlcs.is_empty());
3172         assert!(updates.update_fulfill_htlcs.is_empty());
3173         assert!(updates.update_fail_malformed_htlcs.is_empty());
3174         assert_eq!(updates.update_fail_htlcs.len(), 1);
3175         assert!(updates.update_fee.is_none());
3176         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3177         // At this point first_payment_hash has dropped out of the latest two commitment
3178         // transactions that nodes[1] is tracking...
3179         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3180         check_added_monitors!(nodes[1], 1);
3181         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3182         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3183         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3184         check_added_monitors!(nodes[2], 1);
3185
3186         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3187         // on nodes[2]'s RAA.
3188         let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3189         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3190         let logger = test_utils::TestLogger::new();
3191         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();
3192         nodes[1].node.send_payment(&route, fourth_payment_hash, &None).unwrap();
3193         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3194         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3195         check_added_monitors!(nodes[1], 0);
3196
3197         if deliver_bs_raa {
3198                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3199                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3200                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3201                 check_added_monitors!(nodes[1], 1);
3202                 let events = nodes[1].node.get_and_clear_pending_events();
3203                 assert_eq!(events.len(), 1);
3204                 match events[0] {
3205                         Event::PendingHTLCsForwardable { .. } => { },
3206                         _ => panic!("Unexpected event"),
3207                 };
3208                 // Deliberately don't process the pending fail-back so they all fail back at once after
3209                 // block connection just like the !deliver_bs_raa case
3210         }
3211
3212         let mut failed_htlcs = HashSet::new();
3213         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3214
3215         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
3216         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3217         check_added_monitors!(nodes[1], 1);
3218         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
3219
3220         let events = nodes[1].node.get_and_clear_pending_events();
3221         assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
3222         match events[0] {
3223                 Event::PaymentFailed { ref payment_hash, .. } => {
3224                         assert_eq!(*payment_hash, fourth_payment_hash);
3225                 },
3226                 _ => panic!("Unexpected event"),
3227         }
3228         if !deliver_bs_raa {
3229                 match events[1] {
3230                         Event::PendingHTLCsForwardable { .. } => { },
3231                         _ => panic!("Unexpected event"),
3232                 };
3233         }
3234         nodes[1].node.process_pending_htlc_forwards();
3235         check_added_monitors!(nodes[1], 1);
3236
3237         let events = nodes[1].node.get_and_clear_pending_msg_events();
3238         assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
3239         match events[if deliver_bs_raa { 1 } else { 0 }] {
3240                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3241                 _ => panic!("Unexpected event"),
3242         }
3243         if deliver_bs_raa {
3244                 match events[0] {
3245                         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, .. } } => {
3246                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3247                                 assert_eq!(update_add_htlcs.len(), 1);
3248                                 assert!(update_fulfill_htlcs.is_empty());
3249                                 assert!(update_fail_htlcs.is_empty());
3250                                 assert!(update_fail_malformed_htlcs.is_empty());
3251                         },
3252                         _ => panic!("Unexpected event"),
3253                 }
3254         }
3255         match events[if deliver_bs_raa { 2 } else { 1 }] {
3256                 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, .. } } => {
3257                         assert!(update_add_htlcs.is_empty());
3258                         assert_eq!(update_fail_htlcs.len(), 3);
3259                         assert!(update_fulfill_htlcs.is_empty());
3260                         assert!(update_fail_malformed_htlcs.is_empty());
3261                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3262
3263                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3264                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3265                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3266
3267                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3268
3269                         let events = nodes[0].node.get_and_clear_pending_msg_events();
3270                         // If we delivered B's RAA we got an unknown preimage error, not something
3271                         // that we should update our routing table for.
3272                         assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
3273                         for event in events {
3274                                 match event {
3275                                         MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3276                                         _ => panic!("Unexpected event"),
3277                                 }
3278                         }
3279                         let events = nodes[0].node.get_and_clear_pending_events();
3280                         assert_eq!(events.len(), 3);
3281                         match events[0] {
3282                                 Event::PaymentFailed { ref payment_hash, .. } => {
3283                                         assert!(failed_htlcs.insert(payment_hash.0));
3284                                 },
3285                                 _ => panic!("Unexpected event"),
3286                         }
3287                         match events[1] {
3288                                 Event::PaymentFailed { ref payment_hash, .. } => {
3289                                         assert!(failed_htlcs.insert(payment_hash.0));
3290                                 },
3291                                 _ => panic!("Unexpected event"),
3292                         }
3293                         match events[2] {
3294                                 Event::PaymentFailed { ref payment_hash, .. } => {
3295                                         assert!(failed_htlcs.insert(payment_hash.0));
3296                                 },
3297                                 _ => panic!("Unexpected event"),
3298                         }
3299                 },
3300                 _ => panic!("Unexpected event"),
3301         }
3302
3303         assert!(failed_htlcs.contains(&first_payment_hash.0));
3304         assert!(failed_htlcs.contains(&second_payment_hash.0));
3305         assert!(failed_htlcs.contains(&third_payment_hash.0));
3306 }
3307
3308 #[test]
3309 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3310         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3311         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3312         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3313         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3314 }
3315
3316 #[test]
3317 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3318         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3319         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3320         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3321         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3322 }
3323
3324 #[test]
3325 fn fail_backward_pending_htlc_upon_channel_failure() {
3326         let chanmon_cfgs = create_chanmon_cfgs(2);
3327         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3328         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3329         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3330         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3331         let logger = test_utils::TestLogger::new();
3332
3333         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3334         {
3335                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
3336                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3337                 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();
3338                 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
3339                 check_added_monitors!(nodes[0], 1);
3340
3341                 let payment_event = {
3342                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3343                         assert_eq!(events.len(), 1);
3344                         SendEvent::from_event(events.remove(0))
3345                 };
3346                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3347                 assert_eq!(payment_event.msgs.len(), 1);
3348         }
3349
3350         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3351         let (_, failed_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3352         {
3353                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3354                 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();
3355                 nodes[0].node.send_payment(&route, failed_payment_hash, &None).unwrap();
3356                 check_added_monitors!(nodes[0], 0);
3357
3358                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3359         }
3360
3361         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3362         {
3363                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[1]);
3364
3365                 let secp_ctx = Secp256k1::new();
3366                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3367                 let current_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
3368                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3369                 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();
3370                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &None, current_height).unwrap();
3371                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3372                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3373
3374                 // Send a 0-msat update_add_htlc to fail the channel.
3375                 let update_add_htlc = msgs::UpdateAddHTLC {
3376                         channel_id: chan.2,
3377                         htlc_id: 0,
3378                         amount_msat: 0,
3379                         payment_hash,
3380                         cltv_expiry,
3381                         onion_routing_packet,
3382                 };
3383                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3384         }
3385
3386         // Check that Alice fails backward the pending HTLC from the second payment.
3387         expect_payment_failed!(nodes[0], failed_payment_hash, true);
3388         check_closed_broadcast!(nodes[0], true);
3389         check_added_monitors!(nodes[0], 1);
3390 }
3391
3392 #[test]
3393 fn test_htlc_ignore_latest_remote_commitment() {
3394         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3395         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3396         let chanmon_cfgs = create_chanmon_cfgs(2);
3397         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3398         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3399         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3400         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3401
3402         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3403         nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
3404         check_closed_broadcast!(nodes[0], false);
3405         check_added_monitors!(nodes[0], 1);
3406
3407         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3408         assert_eq!(node_txn.len(), 2);
3409
3410         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3411         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3412         check_closed_broadcast!(nodes[1], false);
3413         check_added_monitors!(nodes[1], 1);
3414
3415         // Duplicate the connect_block call since this may happen due to other listeners
3416         // registering new transactions
3417         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3418 }
3419
3420 #[test]
3421 fn test_force_close_fail_back() {
3422         // Check which HTLCs are failed-backwards on channel force-closure
3423         let chanmon_cfgs = create_chanmon_cfgs(3);
3424         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3425         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3426         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3427         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3428         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3429         let logger = test_utils::TestLogger::new();
3430
3431         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3432
3433         let mut payment_event = {
3434                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3435                 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();
3436                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
3437                 check_added_monitors!(nodes[0], 1);
3438
3439                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3440                 assert_eq!(events.len(), 1);
3441                 SendEvent::from_event(events.remove(0))
3442         };
3443
3444         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3445         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3446
3447         expect_pending_htlcs_forwardable!(nodes[1]);
3448
3449         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3450         assert_eq!(events_2.len(), 1);
3451         payment_event = SendEvent::from_event(events_2.remove(0));
3452         assert_eq!(payment_event.msgs.len(), 1);
3453
3454         check_added_monitors!(nodes[1], 1);
3455         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3456         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3457         check_added_monitors!(nodes[2], 1);
3458         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3459
3460         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3461         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3462         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3463
3464         nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id).unwrap();
3465         check_closed_broadcast!(nodes[2], false);
3466         check_added_monitors!(nodes[2], 1);
3467         let tx = {
3468                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3469                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3470                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3471                 // back to nodes[1] upon timeout otherwise.
3472                 assert_eq!(node_txn.len(), 1);
3473                 node_txn.remove(0)
3474         };
3475
3476         let block = Block {
3477                 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
3478                 txdata: vec![tx.clone()],
3479         };
3480         connect_block(&nodes[1], &block, 1);
3481
3482         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3483         check_closed_broadcast!(nodes[1], false);
3484         check_added_monitors!(nodes[1], 1);
3485
3486         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3487         {
3488                 let mut monitors = nodes[2].chain_monitor.chain_monitor.monitors.lock().unwrap();
3489                 monitors.get_mut(&OutPoint{ txid: Txid::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), index: 0 }).unwrap()
3490                         .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &&logger);
3491         }
3492         connect_block(&nodes[2], &block, 1);
3493         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3494         assert_eq!(node_txn.len(), 1);
3495         assert_eq!(node_txn[0].input.len(), 1);
3496         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3497         assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3498         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3499
3500         check_spends!(node_txn[0], tx);
3501 }
3502
3503 #[test]
3504 fn test_unconf_chan() {
3505         // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
3506         let chanmon_cfgs = create_chanmon_cfgs(2);
3507         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3508         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3509         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3510         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3511
3512         let channel_state = nodes[0].node.channel_state.lock().unwrap();
3513         assert_eq!(channel_state.by_id.len(), 1);
3514         assert_eq!(channel_state.short_to_id.len(), 1);
3515         mem::drop(channel_state);
3516
3517         let mut headers = Vec::new();
3518         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3519         headers.push(header.clone());
3520         for _i in 2..100 {
3521                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3522                 headers.push(header.clone());
3523         }
3524         while !headers.is_empty() {
3525                 nodes[0].node.block_disconnected(&headers.pop().unwrap());
3526         }
3527         check_closed_broadcast!(nodes[0], false);
3528         check_added_monitors!(nodes[0], 1);
3529         let channel_state = nodes[0].node.channel_state.lock().unwrap();
3530         assert_eq!(channel_state.by_id.len(), 0);
3531         assert_eq!(channel_state.short_to_id.len(), 0);
3532 }
3533
3534 #[test]
3535 fn test_simple_peer_disconnect() {
3536         // Test that we can reconnect when there are no lost messages
3537         let chanmon_cfgs = create_chanmon_cfgs(3);
3538         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3539         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3540         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3541         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3542         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3543
3544         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3545         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3546         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3547
3548         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3549         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3550         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3551         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1, 1_000_000);
3552
3553         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3554         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3555         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3556
3557         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3558         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3559         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3560         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3561
3562         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3563         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3564
3565         claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3, 1_000_000);
3566         fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
3567
3568         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3569         {
3570                 let events = nodes[0].node.get_and_clear_pending_events();
3571                 assert_eq!(events.len(), 2);
3572                 match events[0] {
3573                         Event::PaymentSent { payment_preimage } => {
3574                                 assert_eq!(payment_preimage, payment_preimage_3);
3575                         },
3576                         _ => panic!("Unexpected event"),
3577                 }
3578                 match events[1] {
3579                         Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
3580                                 assert_eq!(payment_hash, payment_hash_5);
3581                                 assert!(rejected_by_dest);
3582                         },
3583                         _ => panic!("Unexpected event"),
3584                 }
3585         }
3586
3587         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4, 1_000_000);
3588         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3589 }
3590
3591 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
3592         // Test that we can reconnect when in-flight HTLC updates get dropped
3593         let chanmon_cfgs = create_chanmon_cfgs(2);
3594         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3595         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3596         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3597         if messages_delivered == 0 {
3598                 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3599                 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3600         } else {
3601                 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3602         }
3603
3604         let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
3605
3606         let logger = test_utils::TestLogger::new();
3607         let payment_event = {
3608                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3609                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3610                         &nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3611                         &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3612                 nodes[0].node.send_payment(&route, payment_hash_1, &None).unwrap();
3613                 check_added_monitors!(nodes[0], 1);
3614
3615                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3616                 assert_eq!(events.len(), 1);
3617                 SendEvent::from_event(events.remove(0))
3618         };
3619         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3620
3621         if messages_delivered < 2 {
3622                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3623         } else {
3624                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3625                 if messages_delivered >= 3 {
3626                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3627                         check_added_monitors!(nodes[1], 1);
3628                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3629
3630                         if messages_delivered >= 4 {
3631                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3632                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3633                                 check_added_monitors!(nodes[0], 1);
3634
3635                                 if messages_delivered >= 5 {
3636                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3637                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3638                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3639                                         check_added_monitors!(nodes[0], 1);
3640
3641                                         if messages_delivered >= 6 {
3642                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3643                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3644                                                 check_added_monitors!(nodes[1], 1);
3645                                         }
3646                                 }
3647                         }
3648                 }
3649         }
3650
3651         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3652         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3653         if messages_delivered < 3 {
3654                 // Even if the funding_locked messages get exchanged, as long as nothing further was
3655                 // received on either side, both sides will need to resend them.
3656                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
3657         } else if messages_delivered == 3 {
3658                 // nodes[0] still wants its RAA + commitment_signed
3659                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
3660         } else if messages_delivered == 4 {
3661                 // nodes[0] still wants its commitment_signed
3662                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3663         } else if messages_delivered == 5 {
3664                 // nodes[1] still wants its final RAA
3665                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3666         } else if messages_delivered == 6 {
3667                 // Everything was delivered...
3668                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3669         }
3670
3671         let events_1 = nodes[1].node.get_and_clear_pending_events();
3672         assert_eq!(events_1.len(), 1);
3673         match events_1[0] {
3674                 Event::PendingHTLCsForwardable { .. } => { },
3675                 _ => panic!("Unexpected event"),
3676         };
3677
3678         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3679         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3680         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3681
3682         nodes[1].node.process_pending_htlc_forwards();
3683
3684         let events_2 = nodes[1].node.get_and_clear_pending_events();
3685         assert_eq!(events_2.len(), 1);
3686         match events_2[0] {
3687                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
3688                         assert_eq!(payment_hash_1, *payment_hash);
3689                         assert_eq!(*payment_secret, None);
3690                         assert_eq!(amt, 1000000);
3691                 },
3692                 _ => panic!("Unexpected event"),
3693         }
3694
3695         nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000);
3696         check_added_monitors!(nodes[1], 1);
3697
3698         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3699         assert_eq!(events_3.len(), 1);
3700         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3701                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3702                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3703                         assert!(updates.update_add_htlcs.is_empty());
3704                         assert!(updates.update_fail_htlcs.is_empty());
3705                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3706                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3707                         assert!(updates.update_fee.is_none());
3708                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3709                 },
3710                 _ => panic!("Unexpected event"),
3711         };
3712
3713         if messages_delivered >= 1 {
3714                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3715
3716                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3717                 assert_eq!(events_4.len(), 1);
3718                 match events_4[0] {
3719                         Event::PaymentSent { ref payment_preimage } => {
3720                                 assert_eq!(payment_preimage_1, *payment_preimage);
3721                         },
3722                         _ => panic!("Unexpected event"),
3723                 }
3724
3725                 if messages_delivered >= 2 {
3726                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3727                         check_added_monitors!(nodes[0], 1);
3728                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3729
3730                         if messages_delivered >= 3 {
3731                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3732                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3733                                 check_added_monitors!(nodes[1], 1);
3734
3735                                 if messages_delivered >= 4 {
3736                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3737                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3738                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3739                                         check_added_monitors!(nodes[1], 1);
3740
3741                                         if messages_delivered >= 5 {
3742                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3743                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3744                                                 check_added_monitors!(nodes[0], 1);
3745                                         }
3746                                 }
3747                         }
3748                 }
3749         }
3750
3751         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3752         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3753         if messages_delivered < 2 {
3754                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
3755                 //TODO: Deduplicate PaymentSent events, then enable this if:
3756                 //if messages_delivered < 1 {
3757                         let events_4 = nodes[0].node.get_and_clear_pending_events();
3758                         assert_eq!(events_4.len(), 1);
3759                         match events_4[0] {
3760                                 Event::PaymentSent { ref payment_preimage } => {
3761                                         assert_eq!(payment_preimage_1, *payment_preimage);
3762                                 },
3763                                 _ => panic!("Unexpected event"),
3764                         }
3765                 //}
3766         } else if messages_delivered == 2 {
3767                 // nodes[0] still wants its RAA + commitment_signed
3768                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
3769         } else if messages_delivered == 3 {
3770                 // nodes[0] still wants its commitment_signed
3771                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
3772         } else if messages_delivered == 4 {
3773                 // nodes[1] still wants its final RAA
3774                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3775         } else if messages_delivered == 5 {
3776                 // Everything was delivered...
3777                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3778         }
3779
3780         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3781         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3782         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3783
3784         // Channel should still work fine...
3785         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3786         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3787                 &nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3788                 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3789         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3790         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3791 }
3792
3793 #[test]
3794 fn test_drop_messages_peer_disconnect_a() {
3795         do_test_drop_messages_peer_disconnect(0);
3796         do_test_drop_messages_peer_disconnect(1);
3797         do_test_drop_messages_peer_disconnect(2);
3798         do_test_drop_messages_peer_disconnect(3);
3799 }
3800
3801 #[test]
3802 fn test_drop_messages_peer_disconnect_b() {
3803         do_test_drop_messages_peer_disconnect(4);
3804         do_test_drop_messages_peer_disconnect(5);
3805         do_test_drop_messages_peer_disconnect(6);
3806 }
3807
3808 #[test]
3809 fn test_funding_peer_disconnect() {
3810         // Test that we can lock in our funding tx while disconnected
3811         let chanmon_cfgs = create_chanmon_cfgs(2);
3812         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3813         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3814         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3815         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3816
3817         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3818         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3819
3820         confirm_transaction(&nodes[0], &tx);
3821         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3822         assert_eq!(events_1.len(), 1);
3823         match events_1[0] {
3824                 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3825                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3826                 },
3827                 _ => panic!("Unexpected event"),
3828         }
3829
3830         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3831
3832         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3833         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3834
3835         confirm_transaction(&nodes[1], &tx);
3836         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3837         assert_eq!(events_2.len(), 2);
3838         let funding_locked = match events_2[0] {
3839                 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3840                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3841                         msg.clone()
3842                 },
3843                 _ => panic!("Unexpected event"),
3844         };
3845         let bs_announcement_sigs = match events_2[1] {
3846                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3847                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3848                         msg.clone()
3849                 },
3850                 _ => panic!("Unexpected event"),
3851         };
3852
3853         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3854
3855         nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3856         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3857         let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3858         assert_eq!(events_3.len(), 2);
3859         let as_announcement_sigs = match events_3[0] {
3860                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3861                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3862                         msg.clone()
3863                 },
3864                 _ => panic!("Unexpected event"),
3865         };
3866         let (as_announcement, as_update) = match events_3[1] {
3867                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3868                         (msg.clone(), update_msg.clone())
3869                 },
3870                 _ => panic!("Unexpected event"),
3871         };
3872
3873         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3874         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3875         assert_eq!(events_4.len(), 1);
3876         let (_, bs_update) = match events_4[0] {
3877                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3878                         (msg.clone(), update_msg.clone())
3879                 },
3880                 _ => panic!("Unexpected event"),
3881         };
3882
3883         nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3884         nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3885         nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3886
3887         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3888         let logger = test_utils::TestLogger::new();
3889         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();
3890         let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3891         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage, 1_000_000);
3892 }
3893
3894 #[test]
3895 fn test_drop_messages_peer_disconnect_dual_htlc() {
3896         // Test that we can handle reconnecting when both sides of a channel have pending
3897         // commitment_updates when we disconnect.
3898         let chanmon_cfgs = create_chanmon_cfgs(2);
3899         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3900         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3901         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3902         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3903         let logger = test_utils::TestLogger::new();
3904
3905         let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3906
3907         // Now try to send a second payment which will fail to send
3908         let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
3909         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3910         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();
3911         nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
3912         check_added_monitors!(nodes[0], 1);
3913
3914         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3915         assert_eq!(events_1.len(), 1);
3916         match events_1[0] {
3917                 MessageSendEvent::UpdateHTLCs { .. } => {},
3918                 _ => panic!("Unexpected event"),
3919         }
3920
3921         assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000));
3922         check_added_monitors!(nodes[1], 1);
3923
3924         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3925         assert_eq!(events_2.len(), 1);
3926         match events_2[0] {
3927                 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 } } => {
3928                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3929                         assert!(update_add_htlcs.is_empty());
3930                         assert_eq!(update_fulfill_htlcs.len(), 1);
3931                         assert!(update_fail_htlcs.is_empty());
3932                         assert!(update_fail_malformed_htlcs.is_empty());
3933                         assert!(update_fee.is_none());
3934
3935                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3936                         let events_3 = nodes[0].node.get_and_clear_pending_events();
3937                         assert_eq!(events_3.len(), 1);
3938                         match events_3[0] {
3939                                 Event::PaymentSent { ref payment_preimage } => {
3940                                         assert_eq!(*payment_preimage, payment_preimage_1);
3941                                 },
3942                                 _ => panic!("Unexpected event"),
3943                         }
3944
3945                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3946                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3947                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3948                         check_added_monitors!(nodes[0], 1);
3949                 },
3950                 _ => panic!("Unexpected event"),
3951         }
3952
3953         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3954         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3955
3956         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3957         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3958         assert_eq!(reestablish_1.len(), 1);
3959         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3960         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3961         assert_eq!(reestablish_2.len(), 1);
3962
3963         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3964         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3965         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3966         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3967
3968         assert!(as_resp.0.is_none());
3969         assert!(bs_resp.0.is_none());
3970
3971         assert!(bs_resp.1.is_none());
3972         assert!(bs_resp.2.is_none());
3973
3974         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3975
3976         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3977         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3978         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3979         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3980         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3981         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
3982         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
3983         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3984         // No commitment_signed so get_event_msg's assert(len == 1) passes
3985         check_added_monitors!(nodes[1], 1);
3986
3987         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
3988         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3989         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3990         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3991         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3992         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3993         assert!(bs_second_commitment_signed.update_fee.is_none());
3994         check_added_monitors!(nodes[1], 1);
3995
3996         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3997         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3998         assert!(as_commitment_signed.update_add_htlcs.is_empty());
3999         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4000         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4001         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4002         assert!(as_commitment_signed.update_fee.is_none());
4003         check_added_monitors!(nodes[0], 1);
4004
4005         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4006         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4007         // No commitment_signed so get_event_msg's assert(len == 1) passes
4008         check_added_monitors!(nodes[0], 1);
4009
4010         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4011         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4012         // No commitment_signed so get_event_msg's assert(len == 1) passes
4013         check_added_monitors!(nodes[1], 1);
4014
4015         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4016         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4017         check_added_monitors!(nodes[1], 1);
4018
4019         expect_pending_htlcs_forwardable!(nodes[1]);
4020
4021         let events_5 = nodes[1].node.get_and_clear_pending_events();
4022         assert_eq!(events_5.len(), 1);
4023         match events_5[0] {
4024                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt: _ } => {
4025                         assert_eq!(payment_hash_2, *payment_hash);
4026                         assert_eq!(*payment_secret, None);
4027                 },
4028                 _ => panic!("Unexpected event"),
4029         }
4030
4031         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4032         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4033         check_added_monitors!(nodes[0], 1);
4034
4035         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
4036 }
4037
4038 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4039         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4040         // to avoid our counterparty failing the channel.
4041         let chanmon_cfgs = create_chanmon_cfgs(2);
4042         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4043         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4044         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4045
4046         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4047         let logger = test_utils::TestLogger::new();
4048
4049         let our_payment_hash = if send_partial_mpp {
4050                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4051                 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();
4052                 let (_, our_payment_hash) = get_payment_preimage_hash!(&nodes[0]);
4053                 let payment_secret = PaymentSecret([0xdb; 32]);
4054                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4055                 // indicates there are more HTLCs coming.
4056                 nodes[0].node.send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200000, CHAN_CONFIRM_DEPTH).unwrap();
4057                 check_added_monitors!(nodes[0], 1);
4058                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4059                 assert_eq!(events.len(), 1);
4060                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4061                 // hop should *not* yet generate any PaymentReceived event(s).
4062                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false);
4063                 our_payment_hash
4064         } else {
4065                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4066         };
4067
4068         let mut block = Block {
4069                 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4070                 txdata: vec![],
4071         };
4072         connect_block(&nodes[0], &block, 101);
4073         connect_block(&nodes[1], &block, 101);
4074         for i in 102..TEST_FINAL_CLTV + 100 + 1 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
4075                 block.header.prev_blockhash = block.block_hash();
4076                 connect_block(&nodes[0], &block, i);
4077                 connect_block(&nodes[1], &block, i);
4078         }
4079
4080         expect_pending_htlcs_forwardable!(nodes[1]);
4081
4082         check_added_monitors!(nodes[1], 1);
4083         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4084         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4085         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4086         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4087         assert!(htlc_timeout_updates.update_fee.is_none());
4088
4089         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4090         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4091         // 100_000 msat as u64, followed by a height of 123 as u32
4092         let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4093         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(123));
4094         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4095 }
4096
4097 #[test]
4098 fn test_htlc_timeout() {
4099         do_test_htlc_timeout(true);
4100         do_test_htlc_timeout(false);
4101 }
4102
4103 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4104         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4105         let chanmon_cfgs = create_chanmon_cfgs(3);
4106         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4107         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4108         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4109         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4110         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4111         let logger = test_utils::TestLogger::new();
4112
4113         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4114         let (_, first_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4115         {
4116                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4117                 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();
4118                 nodes[1].node.send_payment(&route, first_payment_hash, &None).unwrap();
4119         }
4120         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4121         check_added_monitors!(nodes[1], 1);
4122
4123         // Now attempt to route a second payment, which should be placed in the holding cell
4124         let (_, second_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4125         if forwarded_htlc {
4126                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4127                 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();
4128                 nodes[0].node.send_payment(&route, second_payment_hash, &None).unwrap();
4129                 check_added_monitors!(nodes[0], 1);
4130                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4131                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4132                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4133                 expect_pending_htlcs_forwardable!(nodes[1]);
4134                 check_added_monitors!(nodes[1], 0);
4135         } else {
4136                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4137                 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();
4138                 nodes[1].node.send_payment(&route, second_payment_hash, &None).unwrap();
4139                 check_added_monitors!(nodes[1], 0);
4140         }
4141
4142         let mut block = Block {
4143                 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4144                 txdata: vec![],
4145         };
4146         connect_block(&nodes[1], &block, 101);
4147         for i in 102..TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
4148                 block.header.prev_blockhash = block.block_hash();
4149                 connect_block(&nodes[1], &block, i);
4150         }
4151
4152         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4153         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4154
4155         block.header.prev_blockhash = block.block_hash();
4156         connect_block(&nodes[1], &block, TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS);
4157
4158         if forwarded_htlc {
4159                 expect_pending_htlcs_forwardable!(nodes[1]);
4160                 check_added_monitors!(nodes[1], 1);
4161                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4162                 assert_eq!(fail_commit.len(), 1);
4163                 match fail_commit[0] {
4164                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4165                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4166                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4167                         },
4168                         _ => unreachable!(),
4169                 }
4170                 expect_payment_failed!(nodes[0], second_payment_hash, false);
4171                 if let &MessageSendEvent::PaymentFailureNetworkUpdate { ref update } = &nodes[0].node.get_and_clear_pending_msg_events()[0] {
4172                         match update {
4173                                 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {},
4174                                 _ => panic!("Unexpected event"),
4175                         }
4176                 } else {
4177                         panic!("Unexpected event");
4178                 }
4179         } else {
4180                 expect_payment_failed!(nodes[1], second_payment_hash, true);
4181         }
4182 }
4183
4184 #[test]
4185 fn test_holding_cell_htlc_add_timeouts() {
4186         do_test_holding_cell_htlc_add_timeouts(false);
4187         do_test_holding_cell_htlc_add_timeouts(true);
4188 }
4189
4190 #[test]
4191 fn test_invalid_channel_announcement() {
4192         //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
4193         let secp_ctx = Secp256k1::new();
4194         let chanmon_cfgs = create_chanmon_cfgs(2);
4195         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4196         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4197         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4198
4199         let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
4200
4201         let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
4202         let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
4203         let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4204         let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4205
4206         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 } );
4207
4208         let as_bitcoin_key = as_chan.get_keys().inner.holder_channel_pubkeys.funding_pubkey;
4209         let bs_bitcoin_key = bs_chan.get_keys().inner.holder_channel_pubkeys.funding_pubkey;
4210
4211         let as_network_key = nodes[0].node.get_our_node_id();
4212         let bs_network_key = nodes[1].node.get_our_node_id();
4213
4214         let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
4215
4216         let mut chan_announcement;
4217
4218         macro_rules! dummy_unsigned_msg {
4219                 () => {
4220                         msgs::UnsignedChannelAnnouncement {
4221                                 features: ChannelFeatures::known(),
4222                                 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4223                                 short_channel_id: as_chan.get_short_channel_id().unwrap(),
4224                                 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
4225                                 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
4226                                 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
4227                                 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
4228                                 excess_data: Vec::new(),
4229                         };
4230                 }
4231         }
4232
4233         macro_rules! sign_msg {
4234                 ($unsigned_msg: expr) => {
4235                         let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
4236                         let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_keys().inner.funding_key);
4237                         let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_keys().inner.funding_key);
4238                         let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
4239                         let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
4240                         chan_announcement = msgs::ChannelAnnouncement {
4241                                 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
4242                                 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
4243                                 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
4244                                 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
4245                                 contents: $unsigned_msg
4246                         }
4247                 }
4248         }
4249
4250         let unsigned_msg = dummy_unsigned_msg!();
4251         sign_msg!(unsigned_msg);
4252         assert_eq!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap(), true);
4253         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 } );
4254
4255         // Configured with Network::Testnet
4256         let mut unsigned_msg = dummy_unsigned_msg!();
4257         unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.block_hash();
4258         sign_msg!(unsigned_msg);
4259         assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4260
4261         let mut unsigned_msg = dummy_unsigned_msg!();
4262         unsigned_msg.chain_hash = BlockHash::hash(&[1,2,3,4,5,6,7,8,9]);
4263         sign_msg!(unsigned_msg);
4264         assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4265 }
4266
4267 #[test]
4268 fn test_no_txn_manager_serialize_deserialize() {
4269         let chanmon_cfgs = create_chanmon_cfgs(2);
4270         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4271         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4272         let logger: test_utils::TestLogger;
4273         let fee_estimator: test_utils::TestFeeEstimator;
4274         let persister: test_utils::TestPersister;
4275         let new_chain_monitor: test_utils::TestChainMonitor;
4276         let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4277         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4278
4279         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4280
4281         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4282
4283         let nodes_0_serialized = nodes[0].node.encode();
4284         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4285         nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4286
4287         logger = test_utils::TestLogger::new();
4288         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4289         persister = test_utils::TestPersister::new();
4290         let keys_manager = &chanmon_cfgs[0].keys_manager;
4291         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4292         nodes[0].chain_monitor = &new_chain_monitor;
4293         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4294         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(
4295                 &mut chan_0_monitor_read, keys_manager).unwrap();
4296         assert!(chan_0_monitor_read.is_empty());
4297
4298         let mut nodes_0_read = &nodes_0_serialized[..];
4299         let config = UserConfig::default();
4300         let (_, nodes_0_deserialized_tmp) = {
4301                 let mut channel_monitors = HashMap::new();
4302                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4303                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4304                         default_config: config,
4305                         keys_manager,
4306                         fee_estimator: &fee_estimator,
4307                         chain_monitor: nodes[0].chain_monitor,
4308                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4309                         logger: &logger,
4310                         channel_monitors,
4311                 }).unwrap()
4312         };
4313         nodes_0_deserialized = nodes_0_deserialized_tmp;
4314         assert!(nodes_0_read.is_empty());
4315
4316         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4317         nodes[0].node = &nodes_0_deserialized;
4318         assert_eq!(nodes[0].node.list_channels().len(), 1);
4319         check_added_monitors!(nodes[0], 1);
4320
4321         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4322         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4323         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4324         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4325
4326         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4327         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4328         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4329         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4330
4331         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4332         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4333         for node in nodes.iter() {
4334                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4335                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4336                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4337         }
4338
4339         send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4340 }
4341
4342 #[test]
4343 fn test_manager_serialize_deserialize_events() {
4344         // This test makes sure the events field in ChannelManager survives de/serialization
4345         let chanmon_cfgs = create_chanmon_cfgs(2);
4346         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4347         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4348         let fee_estimator: test_utils::TestFeeEstimator;
4349         let persister: test_utils::TestPersister;
4350         let logger: test_utils::TestLogger;
4351         let new_chain_monitor: test_utils::TestChainMonitor;
4352         let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4353         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4354
4355         // Start creating a channel, but stop right before broadcasting the event message FundingBroadcastSafe
4356         let channel_value = 100000;
4357         let push_msat = 10001;
4358         let a_flags = InitFeatures::known();
4359         let b_flags = InitFeatures::known();
4360         let node_a = nodes.remove(0);
4361         let node_b = nodes.remove(0);
4362         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4363         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()));
4364         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()));
4365
4366         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4367
4368         node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
4369         check_added_monitors!(node_a, 0);
4370
4371         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()));
4372         {
4373                 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4374                 assert_eq!(added_monitors.len(), 1);
4375                 assert_eq!(added_monitors[0].0, funding_output);
4376                 added_monitors.clear();
4377         }
4378
4379         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()));
4380         {
4381                 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4382                 assert_eq!(added_monitors.len(), 1);
4383                 assert_eq!(added_monitors[0].0, funding_output);
4384                 added_monitors.clear();
4385         }
4386         // Normally, this is where node_a would check for a FundingBroadcastSafe event, but the test de/serializes first instead
4387
4388         nodes.push(node_a);
4389         nodes.push(node_b);
4390
4391         // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4392         let nodes_0_serialized = nodes[0].node.encode();
4393         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4394         nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4395
4396         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4397         logger = test_utils::TestLogger::new();
4398         persister = test_utils::TestPersister::new();
4399         let keys_manager = &chanmon_cfgs[0].keys_manager;
4400         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4401         nodes[0].chain_monitor = &new_chain_monitor;
4402         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4403         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(
4404                 &mut chan_0_monitor_read, keys_manager).unwrap();
4405         assert!(chan_0_monitor_read.is_empty());
4406
4407         let mut nodes_0_read = &nodes_0_serialized[..];
4408         let config = UserConfig::default();
4409         let (_, nodes_0_deserialized_tmp) = {
4410                 let mut channel_monitors = HashMap::new();
4411                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4412                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4413                         default_config: config,
4414                         keys_manager,
4415                         fee_estimator: &fee_estimator,
4416                         chain_monitor: nodes[0].chain_monitor,
4417                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4418                         logger: &logger,
4419                         channel_monitors,
4420                 }).unwrap()
4421         };
4422         nodes_0_deserialized = nodes_0_deserialized_tmp;
4423         assert!(nodes_0_read.is_empty());
4424
4425         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4426
4427         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4428         nodes[0].node = &nodes_0_deserialized;
4429
4430         // After deserializing, make sure the FundingBroadcastSafe event is still held by the channel manager
4431         let events_4 = nodes[0].node.get_and_clear_pending_events();
4432         assert_eq!(events_4.len(), 1);
4433         match events_4[0] {
4434                 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
4435                         assert_eq!(user_channel_id, 42);
4436                         assert_eq!(*funding_txo, funding_output);
4437                 },
4438                 _ => panic!("Unexpected event"),
4439         };
4440
4441         // Make sure the channel is functioning as though the de/serialization never happened
4442         assert_eq!(nodes[0].node.list_channels().len(), 1);
4443         check_added_monitors!(nodes[0], 1);
4444
4445         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4446         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4447         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4448         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4449
4450         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4451         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4452         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4453         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4454
4455         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4456         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4457         for node in nodes.iter() {
4458                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4459                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4460                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4461         }
4462
4463         send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4464 }
4465
4466 #[test]
4467 fn test_simple_manager_serialize_deserialize() {
4468         let chanmon_cfgs = create_chanmon_cfgs(2);
4469         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4470         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4471         let logger: test_utils::TestLogger;
4472         let fee_estimator: test_utils::TestFeeEstimator;
4473         let persister: test_utils::TestPersister;
4474         let new_chain_monitor: test_utils::TestChainMonitor;
4475         let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4476         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4477         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4478
4479         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4480         let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4481
4482         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4483
4484         let nodes_0_serialized = nodes[0].node.encode();
4485         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4486         nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4487
4488         logger = test_utils::TestLogger::new();
4489         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4490         persister = test_utils::TestPersister::new();
4491         let keys_manager = &chanmon_cfgs[0].keys_manager;
4492         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4493         nodes[0].chain_monitor = &new_chain_monitor;
4494         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4495         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(
4496                 &mut chan_0_monitor_read, keys_manager).unwrap();
4497         assert!(chan_0_monitor_read.is_empty());
4498
4499         let mut nodes_0_read = &nodes_0_serialized[..];
4500         let (_, nodes_0_deserialized_tmp) = {
4501                 let mut channel_monitors = HashMap::new();
4502                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4503                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4504                         default_config: UserConfig::default(),
4505                         keys_manager,
4506                         fee_estimator: &fee_estimator,
4507                         chain_monitor: nodes[0].chain_monitor,
4508                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4509                         logger: &logger,
4510                         channel_monitors,
4511                 }).unwrap()
4512         };
4513         nodes_0_deserialized = nodes_0_deserialized_tmp;
4514         assert!(nodes_0_read.is_empty());
4515
4516         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4517         nodes[0].node = &nodes_0_deserialized;
4518         check_added_monitors!(nodes[0], 1);
4519
4520         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4521
4522         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4523         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage, 1_000_000);
4524 }
4525
4526 #[test]
4527 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4528         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4529         let chanmon_cfgs = create_chanmon_cfgs(4);
4530         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4531         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4532         let logger: test_utils::TestLogger;
4533         let fee_estimator: test_utils::TestFeeEstimator;
4534         let persister: test_utils::TestPersister;
4535         let new_chain_monitor: test_utils::TestChainMonitor;
4536         let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4537         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4538         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4539         create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known());
4540         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4541
4542         let mut node_0_stale_monitors_serialized = Vec::new();
4543         for monitor in nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter() {
4544                 let mut writer = test_utils::TestVecWriter(Vec::new());
4545                 monitor.1.write(&mut writer).unwrap();
4546                 node_0_stale_monitors_serialized.push(writer.0);
4547         }
4548
4549         let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4550
4551         // Serialize the ChannelManager here, but the monitor we keep up-to-date
4552         let nodes_0_serialized = nodes[0].node.encode();
4553
4554         route_payment(&nodes[0], &[&nodes[3]], 1000000);
4555         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4556         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4557         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4558
4559         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4560         // nodes[3])
4561         let mut node_0_monitors_serialized = Vec::new();
4562         for monitor in nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter() {
4563                 let mut writer = test_utils::TestVecWriter(Vec::new());
4564                 monitor.1.write(&mut writer).unwrap();
4565                 node_0_monitors_serialized.push(writer.0);
4566         }
4567
4568         logger = test_utils::TestLogger::new();
4569         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4570         persister = test_utils::TestPersister::new();
4571         let keys_manager = &chanmon_cfgs[0].keys_manager;
4572         new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4573         nodes[0].chain_monitor = &new_chain_monitor;
4574
4575
4576         let mut node_0_stale_monitors = Vec::new();
4577         for serialized in node_0_stale_monitors_serialized.iter() {
4578                 let mut read = &serialized[..];
4579                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read, keys_manager).unwrap();
4580                 assert!(read.is_empty());
4581                 node_0_stale_monitors.push(monitor);
4582         }
4583
4584         let mut node_0_monitors = Vec::new();
4585         for serialized in node_0_monitors_serialized.iter() {
4586                 let mut read = &serialized[..];
4587                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read, keys_manager).unwrap();
4588                 assert!(read.is_empty());
4589                 node_0_monitors.push(monitor);
4590         }
4591
4592         let mut nodes_0_read = &nodes_0_serialized[..];
4593         if let Err(msgs::DecodeError::InvalidValue) =
4594                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4595                 default_config: UserConfig::default(),
4596                 keys_manager,
4597                 fee_estimator: &fee_estimator,
4598                 chain_monitor: nodes[0].chain_monitor,
4599                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4600                 logger: &logger,
4601                 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4602         }) { } else {
4603                 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4604         };
4605
4606         let mut nodes_0_read = &nodes_0_serialized[..];
4607         let (_, nodes_0_deserialized_tmp) =
4608                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4609                 default_config: UserConfig::default(),
4610                 keys_manager,
4611                 fee_estimator: &fee_estimator,
4612                 chain_monitor: nodes[0].chain_monitor,
4613                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4614                 logger: &logger,
4615                 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4616         }).unwrap();
4617         nodes_0_deserialized = nodes_0_deserialized_tmp;
4618         assert!(nodes_0_read.is_empty());
4619
4620         { // Channel close should result in a commitment tx and an HTLC tx
4621                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4622                 assert_eq!(txn.len(), 2);
4623                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4624                 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
4625         }
4626
4627         for monitor in node_0_monitors.drain(..) {
4628                 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4629                 check_added_monitors!(nodes[0], 1);
4630         }
4631         nodes[0].node = &nodes_0_deserialized;
4632
4633         // nodes[1] and nodes[2] have no lost state with nodes[0]...
4634         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4635         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4636         //... and we can even still claim the payment!
4637         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage, 1_000_000);
4638
4639         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4640         let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4641         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4642         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4643         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4644         assert_eq!(msg_events.len(), 1);
4645         if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4646                 match action {
4647                         &ErrorAction::SendErrorMessage { ref msg } => {
4648                                 assert_eq!(msg.channel_id, channel_id);
4649                         },
4650                         _ => panic!("Unexpected event!"),
4651                 }
4652         }
4653 }
4654
4655 macro_rules! check_spendable_outputs {
4656         ($node: expr, $der_idx: expr, $keysinterface: expr, $chan_value: expr) => {
4657                 {
4658                         let events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4659                         let mut txn = Vec::new();
4660                         for event in events {
4661                                 match event {
4662                                         Event::SpendableOutputs { ref outputs } => {
4663                                                 for outp in outputs {
4664                                                         match *outp {
4665                                                                 SpendableOutputDescriptor::StaticOutputCounterpartyPayment { ref outpoint, ref output, ref key_derivation_params } => {
4666                                                                         let input = TxIn {
4667                                                                                 previous_output: outpoint.into_bitcoin_outpoint(),
4668                                                                                 script_sig: Script::new(),
4669                                                                                 sequence: 0,
4670                                                                                 witness: Vec::new(),
4671                                                                         };
4672                                                                         let outp = TxOut {
4673                                                                                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4674                                                                                 value: output.value,
4675                                                                         };
4676                                                                         let mut spend_tx = Transaction {
4677                                                                                 version: 2,
4678                                                                                 lock_time: 0,
4679                                                                                 input: vec![input],
4680                                                                                 output: vec![outp],
4681                                                                         };
4682                                                                         spend_tx.output[0].value -= (spend_tx.get_weight() + 2 + 1 + 73 + 35 + 3) as u64 / 4; // (Max weight + 3 (to round up)) / 4
4683                                                                         let secp_ctx = Secp256k1::new();
4684                                                                         let keys = $keysinterface.derive_channel_keys($chan_value, key_derivation_params.0, key_derivation_params.1);
4685                                                                         let remotepubkey = keys.pubkeys().payment_point;
4686                                                                         let witness_script = Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: remotepubkey}, Network::Testnet).script_pubkey();
4687                                                                         let sighash = Message::from_slice(&bip143::SigHashCache::new(&spend_tx).signature_hash(0, &witness_script, output.value, SigHashType::All)[..]).unwrap();
4688                                                                         let remotesig = secp_ctx.sign(&sighash, &keys.inner.payment_key);
4689                                                                         spend_tx.input[0].witness.push(remotesig.serialize_der().to_vec());
4690                                                                         spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4691                                                                         spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
4692                                                                         txn.push(spend_tx);
4693                                                                 },
4694                                                                 SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref per_commitment_point, ref to_self_delay, ref output, ref key_derivation_params, ref revocation_pubkey } => {
4695                                                                         let input = TxIn {
4696                                                                                 previous_output: outpoint.into_bitcoin_outpoint(),
4697                                                                                 script_sig: Script::new(),
4698                                                                                 sequence: *to_self_delay as u32,
4699                                                                                 witness: Vec::new(),
4700                                                                         };
4701                                                                         let outp = TxOut {
4702                                                                                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4703                                                                                 value: output.value,
4704                                                                         };
4705                                                                         let mut spend_tx = Transaction {
4706                                                                                 version: 2,
4707                                                                                 lock_time: 0,
4708                                                                                 input: vec![input],
4709                                                                                 output: vec![outp],
4710                                                                         };
4711                                                                         let secp_ctx = Secp256k1::new();
4712                                                                         let keys = $keysinterface.derive_channel_keys($chan_value, key_derivation_params.0, key_derivation_params.1);
4713                                                                         if let Ok(delayed_payment_key) = chan_utils::derive_private_key(&secp_ctx, &per_commitment_point, &keys.inner.delayed_payment_base_key) {
4714
4715                                                                                 let delayed_payment_pubkey = PublicKey::from_secret_key(&secp_ctx, &delayed_payment_key);
4716                                                                                 let witness_script = chan_utils::get_revokeable_redeemscript(revocation_pubkey, *to_self_delay, &delayed_payment_pubkey);
4717                                                                                 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
4718                                                                                 let sighash = Message::from_slice(&bip143::SigHashCache::new(&spend_tx).signature_hash(0, &witness_script, output.value, SigHashType::All)[..]).unwrap();
4719                                                                                 let local_delayedsig = secp_ctx.sign(&sighash, &delayed_payment_key);
4720                                                                                 spend_tx.input[0].witness.push(local_delayedsig.serialize_der().to_vec());
4721                                                                                 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4722                                                                                 spend_tx.input[0].witness.push(vec!()); //MINIMALIF
4723                                                                                 spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
4724                                                                         } else { panic!() }
4725                                                                         txn.push(spend_tx);
4726                                                                 },
4727                                                                 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
4728                                                                         let secp_ctx = Secp256k1::new();
4729                                                                         let input = TxIn {
4730                                                                                 previous_output: outpoint.into_bitcoin_outpoint(),
4731                                                                                 script_sig: Script::new(),
4732                                                                                 sequence: 0,
4733                                                                                 witness: Vec::new(),
4734                                                                         };
4735                                                                         let outp = TxOut {
4736                                                                                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4737                                                                                 value: output.value,
4738                                                                         };
4739                                                                         let mut spend_tx = Transaction {
4740                                                                                 version: 2,
4741                                                                                 lock_time: 0,
4742                                                                                 input: vec![input],
4743                                                                                 output: vec![outp.clone()],
4744                                                                         };
4745                                                                         spend_tx.output[0].value -= (spend_tx.get_weight() + 2 + 1 + 73 + 35 + 3) as u64 / 4; // (Max weight + 3 (to round up)) / 4
4746                                                                         let secret = {
4747                                                                                 match ExtendedPrivKey::new_master(Network::Testnet, &$node.node_seed) {
4748                                                                                         Ok(master_key) => {
4749                                                                                                 match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx).expect("key space exhausted")) {
4750                                                                                                         Ok(key) => key,
4751                                                                                                         Err(_) => panic!("Your RNG is busted"),
4752                                                                                                 }
4753                                                                                         }
4754                                                                                         Err(_) => panic!("Your rng is busted"),
4755                                                                                 }
4756                                                                         };
4757                                                                         let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
4758                                                                         let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
4759                                                                         let sighash = Message::from_slice(&bip143::SigHashCache::new(&spend_tx).signature_hash(0, &witness_script, output.value, SigHashType::All)[..]).unwrap();
4760                                                                         let sig = secp_ctx.sign(&sighash, &secret.private_key.key);
4761                                                                         spend_tx.input[0].witness.push(sig.serialize_der().to_vec());
4762                                                                         spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4763                                                                         spend_tx.input[0].witness.push(pubkey.key.serialize().to_vec());
4764                                                                         txn.push(spend_tx);
4765                                                                 },
4766                                                         }
4767                                                 }
4768                                         },
4769                                         _ => panic!("Unexpected event"),
4770                                 };
4771                         }
4772                         txn
4773                 }
4774         }
4775 }
4776
4777 #[test]
4778 fn test_claim_sizeable_push_msat() {
4779         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4780         let chanmon_cfgs = create_chanmon_cfgs(2);
4781         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4782         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4783         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4784
4785         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4786         nodes[1].node.force_close_channel(&chan.2).unwrap();
4787         check_closed_broadcast!(nodes[1], false);
4788         check_added_monitors!(nodes[1], 1);
4789         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4790         assert_eq!(node_txn.len(), 1);
4791         check_spends!(node_txn[0], chan.3);
4792         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
4793
4794         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4795         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4796         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4797
4798         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4799         assert_eq!(spend_txn.len(), 1);
4800         check_spends!(spend_txn[0], node_txn[0]);
4801 }
4802
4803 #[test]
4804 fn test_claim_on_remote_sizeable_push_msat() {
4805         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4806         // to_remote output is encumbered by a P2WPKH
4807         let chanmon_cfgs = create_chanmon_cfgs(2);
4808         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4809         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4810         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4811
4812         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4813         nodes[0].node.force_close_channel(&chan.2).unwrap();
4814         check_closed_broadcast!(nodes[0], false);
4815         check_added_monitors!(nodes[0], 1);
4816
4817         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4818         assert_eq!(node_txn.len(), 1);
4819         check_spends!(node_txn[0], chan.3);
4820         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
4821
4822         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4823         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4824         check_closed_broadcast!(nodes[1], false);
4825         check_added_monitors!(nodes[1], 1);
4826         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4827
4828         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4829         assert_eq!(spend_txn.len(), 1);
4830         check_spends!(spend_txn[0], node_txn[0]);
4831 }
4832
4833 #[test]
4834 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4835         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4836         // to_remote output is encumbered by a P2WPKH
4837
4838         let chanmon_cfgs = create_chanmon_cfgs(2);
4839         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4840         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4841         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4842
4843         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4844         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4845         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4846         assert_eq!(revoked_local_txn[0].input.len(), 1);
4847         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4848
4849         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4850         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4851         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
4852         check_closed_broadcast!(nodes[1], false);
4853         check_added_monitors!(nodes[1], 1);
4854
4855         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4856         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4857         connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4858         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4859
4860         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4861         assert_eq!(spend_txn.len(), 2);
4862         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4863         check_spends!(spend_txn[1], node_txn[0]);
4864 }
4865
4866 #[test]
4867 fn test_static_spendable_outputs_preimage_tx() {
4868         let chanmon_cfgs = create_chanmon_cfgs(2);
4869         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4870         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4871         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4872
4873         // Create some initial channels
4874         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4875
4876         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4877
4878         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4879         assert_eq!(commitment_tx[0].input.len(), 1);
4880         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4881
4882         // Settle A's commitment tx on B's chain
4883         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4884         assert!(nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000));
4885         check_added_monitors!(nodes[1], 1);
4886         connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
4887         check_added_monitors!(nodes[1], 1);
4888         let events = nodes[1].node.get_and_clear_pending_msg_events();
4889         match events[0] {
4890                 MessageSendEvent::UpdateHTLCs { .. } => {},
4891                 _ => panic!("Unexpected event"),
4892         }
4893         match events[1] {
4894                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4895                 _ => panic!("Unexepected event"),
4896         }
4897
4898         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4899         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4900         assert_eq!(node_txn.len(), 3);
4901         check_spends!(node_txn[0], commitment_tx[0]);
4902         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4903         check_spends!(node_txn[1], chan_1.3);
4904         check_spends!(node_txn[2], node_txn[1]);
4905
4906         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4907         connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4908         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4909
4910         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4911         assert_eq!(spend_txn.len(), 1);
4912         check_spends!(spend_txn[0], node_txn[0]);
4913 }
4914
4915 #[test]
4916 fn test_static_spendable_outputs_timeout_tx() {
4917         let chanmon_cfgs = create_chanmon_cfgs(2);
4918         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4919         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4920         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4921
4922         // Create some initial channels
4923         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4924
4925         // Rebalance the network a bit by relaying one payment through all the channels ...
4926         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
4927
4928         let (_, our_payment_hash) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4929
4930         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4931         assert_eq!(commitment_tx[0].input.len(), 1);
4932         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4933
4934         // Settle A's commitment tx on B' chain
4935         let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
4936         connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()] }, 0);
4937         check_added_monitors!(nodes[1], 1);
4938         let events = nodes[1].node.get_and_clear_pending_msg_events();
4939         match events[0] {
4940                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4941                 _ => panic!("Unexpected event"),
4942         }
4943
4944         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4945         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4946         assert_eq!(node_txn.len(), 3); // ChannelManager : 2 (local commitent tx + HTLC-timeout), ChannelMonitor: timeout tx
4947         check_spends!(node_txn[0],  commitment_tx[0].clone());
4948         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4949         check_spends!(node_txn[1], chan_1.3.clone());
4950         check_spends!(node_txn[2], node_txn[1]);
4951
4952         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4953         connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4954         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4955         expect_payment_failed!(nodes[1], our_payment_hash, true);
4956
4957         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4958         assert_eq!(spend_txn.len(), 2); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4959         check_spends!(spend_txn[1], node_txn[0]);
4960 }
4961
4962 #[test]
4963 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4964         let chanmon_cfgs = create_chanmon_cfgs(2);
4965         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4966         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4967         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4968
4969         // Create some initial channels
4970         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4971
4972         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4973         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4974         assert_eq!(revoked_local_txn[0].input.len(), 1);
4975         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4976
4977         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4978
4979         let  header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4980         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
4981         check_closed_broadcast!(nodes[1], false);
4982         check_added_monitors!(nodes[1], 1);
4983
4984         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4985         assert_eq!(node_txn.len(), 2);
4986         assert_eq!(node_txn[0].input.len(), 2);
4987         check_spends!(node_txn[0], revoked_local_txn[0]);
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
4993         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4994         assert_eq!(spend_txn.len(), 1);
4995         check_spends!(spend_txn[0], node_txn[0]);
4996 }
4997
4998 #[test]
4999 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
5000         let mut chanmon_cfgs = create_chanmon_cfgs(2);
5001         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
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         // A will generate HTLC-Timeout from revoked commitment tx
5018         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5019         check_closed_broadcast!(nodes[0], false);
5020         check_added_monitors!(nodes[0], 1);
5021
5022         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5023         assert_eq!(revoked_htlc_txn.len(), 2);
5024         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5025         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5026         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5027         check_spends!(revoked_htlc_txn[1], chan_1.3);
5028
5029         // B will generate justice tx from A's revoked commitment/HTLC tx
5030         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 0);
5031         check_closed_broadcast!(nodes[1], false);
5032         check_added_monitors!(nodes[1], 1);
5033
5034         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5035         assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
5036         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5037         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5038         // transactions next...
5039         assert_eq!(node_txn[0].input.len(), 3);
5040         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5041
5042         assert_eq!(node_txn[1].input.len(), 2);
5043         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
5044         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5045                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5046         } else {
5047                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5048                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5049         }
5050
5051         assert_eq!(node_txn[2].input.len(), 1);
5052         check_spends!(node_txn[2], chan_1.3);
5053
5054         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5055         connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[1].clone()] }, 1);
5056         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5057
5058         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
5059         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5060         assert_eq!(spend_txn.len(), 1);
5061         assert_eq!(spend_txn[0].input.len(), 1);
5062         check_spends!(spend_txn[0], node_txn[1]);
5063 }
5064
5065 #[test]
5066 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
5067         let mut chanmon_cfgs = create_chanmon_cfgs(2);
5068         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
5069         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5070         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5071         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5072
5073         // Create some initial channels
5074         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5075
5076         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5077         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5078         assert_eq!(revoked_local_txn[0].input.len(), 1);
5079         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5080
5081         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
5082         assert_eq!(revoked_local_txn[0].output.len(), 2);
5083
5084         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
5085
5086         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5087         // B will generate HTLC-Success from revoked commitment tx
5088         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5089         check_closed_broadcast!(nodes[1], false);
5090         check_added_monitors!(nodes[1], 1);
5091         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5092
5093         assert_eq!(revoked_htlc_txn.len(), 2);
5094         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5095         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5096         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5097
5098         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5099         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5100         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5101
5102         // A will generate justice tx from B's revoked commitment/HTLC tx
5103         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
5104         check_closed_broadcast!(nodes[0], false);
5105         check_added_monitors!(nodes[0], 1);
5106
5107         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5108         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5109
5110         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5111         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5112         // transactions next...
5113         assert_eq!(node_txn[0].input.len(), 2);
5114         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5115         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5116                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5117         } else {
5118                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5119                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5120         }
5121
5122         assert_eq!(node_txn[1].input.len(), 1);
5123         check_spends!(node_txn[1], revoked_htlc_txn[0]);
5124
5125         check_spends!(node_txn[2], chan_1.3);
5126
5127         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5128         connect_block(&nodes[0], &Block { header: header_1, txdata: vec![node_txn[1].clone()] }, 1);
5129         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5130
5131         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5132         // didn't try to generate any new transactions.
5133
5134         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5135         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5136         assert_eq!(spend_txn.len(), 2);
5137         assert_eq!(spend_txn[0].input.len(), 1);
5138         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5139         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5140         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5141 }
5142
5143 #[test]
5144 fn test_onchain_to_onchain_claim() {
5145         // Test that in case of channel closure, we detect the state of output and claim HTLC
5146         // on downstream peer's remote commitment tx.
5147         // First, have C claim an HTLC against its own latest commitment transaction.
5148         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5149         // channel.
5150         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5151         // gets broadcast.
5152
5153         let chanmon_cfgs = create_chanmon_cfgs(3);
5154         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5155         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5156         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5157
5158         // Create some initial channels
5159         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5160         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5161
5162         // Rebalance the network a bit by relaying one payment through all the channels ...
5163         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5164         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5165
5166         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5167         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5168         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5169         check_spends!(commitment_tx[0], chan_2.3);
5170         nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000);
5171         check_added_monitors!(nodes[2], 1);
5172         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5173         assert!(updates.update_add_htlcs.is_empty());
5174         assert!(updates.update_fail_htlcs.is_empty());
5175         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5176         assert!(updates.update_fail_malformed_htlcs.is_empty());
5177
5178         connect_block(&nodes[2], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
5179         check_closed_broadcast!(nodes[2], false);
5180         check_added_monitors!(nodes[2], 1);
5181
5182         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5183         assert_eq!(c_txn.len(), 3);
5184         assert_eq!(c_txn[0], c_txn[2]);
5185         assert_eq!(commitment_tx[0], c_txn[1]);
5186         check_spends!(c_txn[1], chan_2.3);
5187         check_spends!(c_txn[2], c_txn[1]);
5188         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5189         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5190         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5191         assert_eq!(c_txn[0].lock_time, 0); // Success tx
5192
5193         // 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
5194         connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
5195         {
5196                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5197                 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-timeout tx
5198                 assert_eq!(b_txn.len(), 3);
5199                 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
5200                 check_spends!(b_txn[2], b_txn[1]); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
5201                 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5202                 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5203                 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5204                 check_spends!(b_txn[0], c_txn[1]); // timeout tx on C remote commitment tx, issued by ChannelMonitor
5205                 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5206                 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5207                 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5208                 b_txn.clear();
5209         }
5210         check_added_monitors!(nodes[1], 1);
5211         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5212         check_added_monitors!(nodes[1], 1);
5213         match msg_events[0] {
5214                 MessageSendEvent::BroadcastChannelUpdate {  .. } => {},
5215                 _ => panic!("Unexpected event"),
5216         }
5217         match msg_events[1] {
5218                 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, .. } } => {
5219                         assert!(update_add_htlcs.is_empty());
5220                         assert!(update_fail_htlcs.is_empty());
5221                         assert_eq!(update_fulfill_htlcs.len(), 1);
5222                         assert!(update_fail_malformed_htlcs.is_empty());
5223                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5224                 },
5225                 _ => panic!("Unexpected event"),
5226         };
5227         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5228         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5229         connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
5230         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5231         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5232         assert_eq!(b_txn.len(), 3);
5233         check_spends!(b_txn[1], chan_1.3);
5234         check_spends!(b_txn[2], b_txn[1]);
5235         check_spends!(b_txn[0], commitment_tx[0]);
5236         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5237         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5238         assert_eq!(b_txn[0].lock_time, 0); // Success tx
5239
5240         check_closed_broadcast!(nodes[1], false);
5241         check_added_monitors!(nodes[1], 1);
5242 }
5243
5244 #[test]
5245 fn test_duplicate_payment_hash_one_failure_one_success() {
5246         // Topology : A --> B --> C
5247         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5248         let chanmon_cfgs = create_chanmon_cfgs(3);
5249         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5250         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5251         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5252
5253         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5254         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5255
5256         let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5257         *nodes[0].network_payment_count.borrow_mut() -= 1;
5258         assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
5259
5260         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5261         assert_eq!(commitment_txn[0].input.len(), 1);
5262         check_spends!(commitment_txn[0], chan_2.3);
5263
5264         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5265         connect_block(&nodes[1], &Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
5266         check_closed_broadcast!(nodes[1], false);
5267         check_added_monitors!(nodes[1], 1);
5268
5269         let htlc_timeout_tx;
5270         { // Extract one of the two HTLC-Timeout transaction
5271                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5272                 // ChannelMonitor: timeout tx * 2, ChannelManager: local commitment tx + HTLC-timeout * 2
5273                 assert_eq!(node_txn.len(), 5);
5274                 check_spends!(node_txn[0], commitment_txn[0]);
5275                 assert_eq!(node_txn[0].input.len(), 1);
5276                 check_spends!(node_txn[1], commitment_txn[0]);
5277                 assert_eq!(node_txn[1].input.len(), 1);
5278                 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
5279                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5280                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5281                 check_spends!(node_txn[2], chan_2.3);
5282                 check_spends!(node_txn[3], node_txn[2]);
5283                 check_spends!(node_txn[4], node_txn[2]);
5284                 htlc_timeout_tx = node_txn[1].clone();
5285         }
5286
5287         nodes[2].node.claim_funds(our_payment_preimage, &None, 900_000);
5288         connect_block(&nodes[2], &Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
5289         check_added_monitors!(nodes[2], 3);
5290         let events = nodes[2].node.get_and_clear_pending_msg_events();
5291         match events[0] {
5292                 MessageSendEvent::UpdateHTLCs { .. } => {},
5293                 _ => panic!("Unexpected event"),
5294         }
5295         match events[1] {
5296                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5297                 _ => panic!("Unexepected event"),
5298         }
5299         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5300         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)
5301         check_spends!(htlc_success_txn[2], chan_2.3);
5302         check_spends!(htlc_success_txn[3], htlc_success_txn[2]);
5303         check_spends!(htlc_success_txn[4], htlc_success_txn[2]);
5304         assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
5305         assert_eq!(htlc_success_txn[0].input.len(), 1);
5306         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5307         assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
5308         assert_eq!(htlc_success_txn[1].input.len(), 1);
5309         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5310         assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
5311         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5312         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5313
5314         connect_block(&nodes[1], &Block { header, txdata: vec![htlc_timeout_tx] }, 200);
5315         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 200, true, header.block_hash());
5316         expect_pending_htlcs_forwardable!(nodes[1]);
5317         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5318         assert!(htlc_updates.update_add_htlcs.is_empty());
5319         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5320         assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
5321         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5322         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5323         check_added_monitors!(nodes[1], 1);
5324
5325         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5326         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5327         {
5328                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5329                 let events = nodes[0].node.get_and_clear_pending_msg_events();
5330                 assert_eq!(events.len(), 1);
5331                 match events[0] {
5332                         MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. }  } => {
5333                         },
5334                         _ => { panic!("Unexpected event"); }
5335                 }
5336         }
5337         expect_payment_failed!(nodes[0], duplicate_payment_hash, false);
5338
5339         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5340         connect_block(&nodes[1], &Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
5341         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5342         assert!(updates.update_add_htlcs.is_empty());
5343         assert!(updates.update_fail_htlcs.is_empty());
5344         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5345         assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
5346         assert!(updates.update_fail_malformed_htlcs.is_empty());
5347         check_added_monitors!(nodes[1], 1);
5348
5349         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5350         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5351
5352         let events = nodes[0].node.get_and_clear_pending_events();
5353         match events[0] {
5354                 Event::PaymentSent { ref payment_preimage } => {
5355                         assert_eq!(*payment_preimage, our_payment_preimage);
5356                 }
5357                 _ => panic!("Unexpected event"),
5358         }
5359 }
5360
5361 #[test]
5362 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5363         let chanmon_cfgs = create_chanmon_cfgs(2);
5364         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5365         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5366         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5367
5368         // Create some initial channels
5369         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5370
5371         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5372         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5373         assert_eq!(local_txn[0].input.len(), 1);
5374         check_spends!(local_txn[0], chan_1.3);
5375
5376         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5377         nodes[1].node.claim_funds(payment_preimage, &None, 9_000_000);
5378         check_added_monitors!(nodes[1], 1);
5379         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5380         connect_block(&nodes[1], &Block { header, txdata: vec![local_txn[0].clone()] }, 1);
5381         check_added_monitors!(nodes[1], 1);
5382         let events = nodes[1].node.get_and_clear_pending_msg_events();
5383         match events[0] {
5384                 MessageSendEvent::UpdateHTLCs { .. } => {},
5385                 _ => panic!("Unexpected event"),
5386         }
5387         match events[1] {
5388                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5389                 _ => panic!("Unexepected event"),
5390         }
5391         let node_txn = {
5392                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5393                 assert_eq!(node_txn[0].input.len(), 1);
5394                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5395                 check_spends!(node_txn[0], local_txn[0]);
5396                 vec![node_txn[0].clone(), node_txn[2].clone()]
5397         };
5398
5399         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5400         connect_block(&nodes[1], &Block { header: header_201, txdata: node_txn.clone() }, 201);
5401         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5402
5403         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5404         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5405         assert_eq!(spend_txn.len(), 2);
5406         check_spends!(spend_txn[0], node_txn[0]);
5407         check_spends!(spend_txn[1], node_txn[1]);
5408 }
5409
5410 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5411         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5412         // unrevoked commitment transaction.
5413         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5414         // a remote RAA before they could be failed backwards (and combinations thereof).
5415         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5416         // use the same payment hashes.
5417         // Thus, we use a six-node network:
5418         //
5419         // A \         / E
5420         //    - C - D -
5421         // B /         \ F
5422         // And test where C fails back to A/B when D announces its latest commitment transaction
5423         let chanmon_cfgs = create_chanmon_cfgs(6);
5424         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5425         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
5426         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5427         let logger = test_utils::TestLogger::new();
5428
5429         create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5430         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5431         let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5432         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5433         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5434
5435         // Rebalance and check output sanity...
5436         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000, 500_000);
5437         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000, 500_000);
5438         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5439
5440         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5441         // 0th HTLC:
5442         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
5443         // 1st HTLC:
5444         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
5445         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
5446         let our_node_id = &nodes[1].node.get_our_node_id();
5447         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();
5448         // 2nd HTLC:
5449         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
5450         // 3rd HTLC:
5451         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
5452         // 4th HTLC:
5453         let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5454         // 5th HTLC:
5455         let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5456         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();
5457         // 6th HTLC:
5458         send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
5459         // 7th HTLC:
5460         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
5461
5462         // 8th HTLC:
5463         let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5464         // 9th HTLC:
5465         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();
5466         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
5467
5468         // 10th HTLC:
5469         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
5470         // 11th HTLC:
5471         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();
5472         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
5473
5474         // Double-check that six of the new HTLC were added
5475         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5476         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5477         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5478         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5479
5480         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5481         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5482         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1, &None));
5483         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3, &None));
5484         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5, &None));
5485         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6, &None));
5486         check_added_monitors!(nodes[4], 0);
5487         expect_pending_htlcs_forwardable!(nodes[4]);
5488         check_added_monitors!(nodes[4], 1);
5489
5490         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5491         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5492         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5493         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5494         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5495         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5496
5497         // Fail 3rd below-dust and 7th above-dust HTLCs
5498         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2, &None));
5499         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4, &None));
5500         check_added_monitors!(nodes[5], 0);
5501         expect_pending_htlcs_forwardable!(nodes[5]);
5502         check_added_monitors!(nodes[5], 1);
5503
5504         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5505         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5506         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5507         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5508
5509         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5510
5511         expect_pending_htlcs_forwardable!(nodes[3]);
5512         check_added_monitors!(nodes[3], 1);
5513         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5514         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5515         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5516         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5517         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5518         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5519         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5520         if deliver_last_raa {
5521                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5522         } else {
5523                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5524         }
5525
5526         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5527         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5528         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5529         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5530         //
5531         // We now broadcast the latest commitment transaction, which *should* result in failures for
5532         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5533         // the non-broadcast above-dust HTLCs.
5534         //
5535         // Alternatively, we may broadcast the previous commitment transaction, which should only
5536         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5537         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5538
5539         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5540         if announce_latest {
5541                 connect_block(&nodes[2], &Block { header, txdata: vec![ds_last_commitment_tx[0].clone()]}, 1);
5542         } else {
5543                 connect_block(&nodes[2], &Block { header, txdata: vec![ds_prev_commitment_tx[0].clone()]}, 1);
5544         }
5545         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1, 1, true,  header.block_hash());
5546         check_closed_broadcast!(nodes[2], false);
5547         expect_pending_htlcs_forwardable!(nodes[2]);
5548         check_added_monitors!(nodes[2], 3);
5549
5550         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5551         assert_eq!(cs_msgs.len(), 2);
5552         let mut a_done = false;
5553         for msg in cs_msgs {
5554                 match msg {
5555                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5556                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5557                                 // should be failed-backwards here.
5558                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5559                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5560                                         for htlc in &updates.update_fail_htlcs {
5561                                                 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 });
5562                                         }
5563                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5564                                         assert!(!a_done);
5565                                         a_done = true;
5566                                         &nodes[0]
5567                                 } else {
5568                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5569                                         for htlc in &updates.update_fail_htlcs {
5570                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5571                                         }
5572                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5573                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5574                                         &nodes[1]
5575                                 };
5576                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5577                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5578                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5579                                 if announce_latest {
5580                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5581                                         if *node_id == nodes[0].node.get_our_node_id() {
5582                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5583                                         }
5584                                 }
5585                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5586                         },
5587                         _ => panic!("Unexpected event"),
5588                 }
5589         }
5590
5591         let as_events = nodes[0].node.get_and_clear_pending_events();
5592         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5593         let mut as_failds = HashSet::new();
5594         for event in as_events.iter() {
5595                 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5596                         assert!(as_failds.insert(*payment_hash));
5597                         if *payment_hash != payment_hash_2 {
5598                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5599                         } else {
5600                                 assert!(!rejected_by_dest);
5601                         }
5602                 } else { panic!("Unexpected event"); }
5603         }
5604         assert!(as_failds.contains(&payment_hash_1));
5605         assert!(as_failds.contains(&payment_hash_2));
5606         if announce_latest {
5607                 assert!(as_failds.contains(&payment_hash_3));
5608                 assert!(as_failds.contains(&payment_hash_5));
5609         }
5610         assert!(as_failds.contains(&payment_hash_6));
5611
5612         let bs_events = nodes[1].node.get_and_clear_pending_events();
5613         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5614         let mut bs_failds = HashSet::new();
5615         for event in bs_events.iter() {
5616                 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5617                         assert!(bs_failds.insert(*payment_hash));
5618                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5619                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5620                         } else {
5621                                 assert!(!rejected_by_dest);
5622                         }
5623                 } else { panic!("Unexpected event"); }
5624         }
5625         assert!(bs_failds.contains(&payment_hash_1));
5626         assert!(bs_failds.contains(&payment_hash_2));
5627         if announce_latest {
5628                 assert!(bs_failds.contains(&payment_hash_4));
5629         }
5630         assert!(bs_failds.contains(&payment_hash_5));
5631
5632         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5633         // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
5634         // to unknown-preimage-etc, B should have gotten 2. Thus, in the
5635         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
5636         // PaymentFailureNetworkUpdates.
5637         let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
5638         assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5639         let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5640         assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5641         for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
5642                 match event {
5643                         &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
5644                         _ => panic!("Unexpected event"),
5645                 }
5646         }
5647 }
5648
5649 #[test]
5650 fn test_fail_backwards_latest_remote_announce_a() {
5651         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5652 }
5653
5654 #[test]
5655 fn test_fail_backwards_latest_remote_announce_b() {
5656         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5657 }
5658
5659 #[test]
5660 fn test_fail_backwards_previous_remote_announce() {
5661         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5662         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5663         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5664 }
5665
5666 #[test]
5667 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5668         let chanmon_cfgs = create_chanmon_cfgs(2);
5669         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5670         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5671         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5672
5673         // Create some initial channels
5674         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5675
5676         let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5677         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5678         assert_eq!(local_txn[0].input.len(), 1);
5679         check_spends!(local_txn[0], chan_1.3);
5680
5681         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5682         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5683         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] }, 200);
5684         check_closed_broadcast!(nodes[0], false);
5685         check_added_monitors!(nodes[0], 1);
5686
5687         let htlc_timeout = {
5688                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5689                 assert_eq!(node_txn[0].input.len(), 1);
5690                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5691                 check_spends!(node_txn[0], local_txn[0]);
5692                 node_txn[0].clone()
5693         };
5694
5695         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5696         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
5697         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5698         expect_payment_failed!(nodes[0], our_payment_hash, true);
5699
5700         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5701         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5702         assert_eq!(spend_txn.len(), 2);
5703         check_spends!(spend_txn[0], local_txn[0]);
5704         check_spends!(spend_txn[1], htlc_timeout);
5705 }
5706
5707 #[test]
5708 fn test_key_derivation_params() {
5709         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5710         // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5711         // let us re-derive the channel key set to then derive a delayed_payment_key.
5712
5713         let chanmon_cfgs = create_chanmon_cfgs(3);
5714
5715         // We manually create the node configuration to backup the seed.
5716         let seed = [42; 32];
5717         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5718         let chain_monitor = test_utils::TestChainMonitor::new(Some(&chanmon_cfgs[0].chain_source), &chanmon_cfgs[0].tx_broadcaster, &chanmon_cfgs[0].logger, &chanmon_cfgs[0].fee_estimator, &chanmon_cfgs[0].persister, &keys_manager);
5719         let node = NodeCfg { chain_source: &chanmon_cfgs[0].chain_source, logger: &chanmon_cfgs[0].logger, tx_broadcaster: &chanmon_cfgs[0].tx_broadcaster, fee_estimator: &chanmon_cfgs[0].fee_estimator, chain_monitor, keys_manager: &keys_manager, node_seed: seed };
5720         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5721         node_cfgs.remove(0);
5722         node_cfgs.insert(0, node);
5723
5724         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5725         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5726
5727         // Create some initial channels
5728         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5729         // for node 0
5730         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5731         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5732         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5733
5734         let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5735         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5736         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5737         assert_eq!(local_txn_1[0].input.len(), 1);
5738         check_spends!(local_txn_1[0], chan_1.3);
5739
5740         // We check funding pubkey are unique
5741         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]));
5742         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]));
5743         if from_0_funding_key_0 == from_1_funding_key_0
5744             || from_0_funding_key_0 == from_1_funding_key_1
5745             || from_0_funding_key_1 == from_1_funding_key_0
5746             || from_0_funding_key_1 == from_1_funding_key_1 {
5747                 panic!("Funding pubkeys aren't unique");
5748         }
5749
5750         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5751         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5752         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn_1[0].clone()] }, 200);
5753         check_closed_broadcast!(nodes[0], false);
5754         check_added_monitors!(nodes[0], 1);
5755
5756         let htlc_timeout = {
5757                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5758                 assert_eq!(node_txn[0].input.len(), 1);
5759                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5760                 check_spends!(node_txn[0], local_txn_1[0]);
5761                 node_txn[0].clone()
5762         };
5763
5764         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5765         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
5766         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5767         expect_payment_failed!(nodes[0], our_payment_hash, true);
5768
5769         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5770         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5771         let spend_txn = check_spendable_outputs!(nodes[0], 1, new_keys_manager, 100000);
5772         assert_eq!(spend_txn.len(), 2);
5773         check_spends!(spend_txn[0], local_txn_1[0]);
5774         check_spends!(spend_txn[1], htlc_timeout);
5775 }
5776
5777 #[test]
5778 fn test_static_output_closing_tx() {
5779         let chanmon_cfgs = create_chanmon_cfgs(2);
5780         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5781         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5782         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5783
5784         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5785
5786         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
5787         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5788
5789         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5790         connect_block(&nodes[0], &Block { header, txdata: vec![closing_tx.clone()] }, 0);
5791         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
5792
5793         let spend_txn = check_spendable_outputs!(nodes[0], 2, node_cfgs[0].keys_manager, 100000);
5794         assert_eq!(spend_txn.len(), 1);
5795         check_spends!(spend_txn[0], closing_tx);
5796
5797         connect_block(&nodes[1], &Block { header, txdata: vec![closing_tx.clone()] }, 0);
5798         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
5799
5800         let spend_txn = check_spendable_outputs!(nodes[1], 2, node_cfgs[1].keys_manager, 100000);
5801         assert_eq!(spend_txn.len(), 1);
5802         check_spends!(spend_txn[0], closing_tx);
5803 }
5804
5805 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5806         let chanmon_cfgs = create_chanmon_cfgs(2);
5807         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5808         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5809         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5810         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5811
5812         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5813
5814         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5815         // present in B's local commitment transaction, but none of A's commitment transactions.
5816         assert!(nodes[1].node.claim_funds(our_payment_preimage, &None, if use_dust { 50_000 } else { 3_000_000 }));
5817         check_added_monitors!(nodes[1], 1);
5818
5819         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5820         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5821         let events = nodes[0].node.get_and_clear_pending_events();
5822         assert_eq!(events.len(), 1);
5823         match events[0] {
5824                 Event::PaymentSent { payment_preimage } => {
5825                         assert_eq!(payment_preimage, our_payment_preimage);
5826                 },
5827                 _ => panic!("Unexpected event"),
5828         }
5829
5830         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5831         check_added_monitors!(nodes[0], 1);
5832         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5833         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5834         check_added_monitors!(nodes[1], 1);
5835
5836         let mut block = Block {
5837                 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5838                 txdata: vec![],
5839         };
5840         for i in 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + CHAN_CONFIRM_DEPTH + 1 {
5841                 connect_block(&nodes[1], &block, i);
5842                 block.header.prev_blockhash = block.block_hash();
5843         }
5844         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5845         check_closed_broadcast!(nodes[1], false);
5846         check_added_monitors!(nodes[1], 1);
5847 }
5848
5849 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5850         let chanmon_cfgs = create_chanmon_cfgs(2);
5851         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5852         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5853         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5854         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5855         let logger = test_utils::TestLogger::new();
5856
5857         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5858         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5859         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();
5860         nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
5861         check_added_monitors!(nodes[0], 1);
5862
5863         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5864
5865         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5866         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5867         // to "time out" the HTLC.
5868
5869         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5870
5871         for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5872                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()}, i);
5873                 header.prev_blockhash = header.block_hash();
5874         }
5875         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5876         check_closed_broadcast!(nodes[0], false);
5877         check_added_monitors!(nodes[0], 1);
5878 }
5879
5880 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5881         let chanmon_cfgs = create_chanmon_cfgs(3);
5882         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5883         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5884         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5885         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5886
5887         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5888         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5889         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5890         // actually revoked.
5891         let htlc_value = if use_dust { 50000 } else { 3000000 };
5892         let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5893         assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash, &None));
5894         expect_pending_htlcs_forwardable!(nodes[1]);
5895         check_added_monitors!(nodes[1], 1);
5896
5897         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5898         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5899         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5900         check_added_monitors!(nodes[0], 1);
5901         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5902         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5903         check_added_monitors!(nodes[1], 1);
5904         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5905         check_added_monitors!(nodes[1], 1);
5906         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5907
5908         if check_revoke_no_close {
5909                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5910                 check_added_monitors!(nodes[0], 1);
5911         }
5912
5913         let mut block = Block {
5914                 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5915                 txdata: vec![],
5916         };
5917         for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5918                 connect_block(&nodes[0], &block, i);
5919                 block.header.prev_blockhash = block.block_hash();
5920         }
5921         if !check_revoke_no_close {
5922                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5923                 check_closed_broadcast!(nodes[0], false);
5924                 check_added_monitors!(nodes[0], 1);
5925         } else {
5926                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5927         }
5928 }
5929
5930 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5931 // There are only a few cases to test here:
5932 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5933 //    broadcastable commitment transactions result in channel closure,
5934 //  * its included in an unrevoked-but-previous remote commitment transaction,
5935 //  * its included in the latest remote or local commitment transactions.
5936 // We test each of the three possible commitment transactions individually and use both dust and
5937 // non-dust HTLCs.
5938 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5939 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5940 // tested for at least one of the cases in other tests.
5941 #[test]
5942 fn htlc_claim_single_commitment_only_a() {
5943         do_htlc_claim_local_commitment_only(true);
5944         do_htlc_claim_local_commitment_only(false);
5945
5946         do_htlc_claim_current_remote_commitment_only(true);
5947         do_htlc_claim_current_remote_commitment_only(false);
5948 }
5949
5950 #[test]
5951 fn htlc_claim_single_commitment_only_b() {
5952         do_htlc_claim_previous_remote_commitment_only(true, false);
5953         do_htlc_claim_previous_remote_commitment_only(false, false);
5954         do_htlc_claim_previous_remote_commitment_only(true, true);
5955         do_htlc_claim_previous_remote_commitment_only(false, true);
5956 }
5957
5958 #[test]
5959 #[should_panic]
5960 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5961         let chanmon_cfgs = create_chanmon_cfgs(2);
5962         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5963         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5964         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5965         //Force duplicate channel ids
5966         for node in nodes.iter() {
5967                 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5968         }
5969
5970         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5971         let channel_value_satoshis=10000;
5972         let push_msat=10001;
5973         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5974         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5975         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5976
5977         //Create a second channel with a channel_id collision
5978         assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5979 }
5980
5981 #[test]
5982 fn bolt2_open_channel_sending_node_checks_part2() {
5983         let chanmon_cfgs = create_chanmon_cfgs(2);
5984         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5985         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5986         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5987
5988         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5989         let channel_value_satoshis=2^24;
5990         let push_msat=10001;
5991         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5992
5993         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5994         let channel_value_satoshis=10000;
5995         // Test when push_msat is equal to 1000 * funding_satoshis.
5996         let push_msat=1000*channel_value_satoshis+1;
5997         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5998
5999         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
6000         let channel_value_satoshis=10000;
6001         let push_msat=10001;
6002         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
6003         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6004         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
6005
6006         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
6007         // 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
6008         assert!(node0_to_1_send_open_channel.channel_flags<=1);
6009
6010         // 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.
6011         assert!(BREAKDOWN_TIMEOUT>0);
6012         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
6013
6014         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
6015         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
6016         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
6017
6018         // 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.
6019         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
6020         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
6021         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
6022         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
6023         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6024 }
6025
6026 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6027 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6028 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6029 // is no longer affordable once it's freed.
6030 #[test]
6031 fn test_fail_holding_cell_htlc_upon_free() {
6032         let chanmon_cfgs = create_chanmon_cfgs(2);
6033         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6034         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6035         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6036         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6037         let logger = test_utils::TestLogger::new();
6038
6039         // First nodes[0] generates an update_fee, setting the channel's
6040         // pending_update_fee.
6041         nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 20).unwrap();
6042         check_added_monitors!(nodes[0], 1);
6043
6044         let events = nodes[0].node.get_and_clear_pending_msg_events();
6045         assert_eq!(events.len(), 1);
6046         let (update_msg, commitment_signed) = match events[0] {
6047                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6048                         (update_fee.as_ref(), commitment_signed)
6049                 },
6050                 _ => panic!("Unexpected event"),
6051         };
6052
6053         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6054
6055         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6056         let channel_reserve = chan_stat.channel_reserve_msat;
6057         let feerate = get_feerate!(nodes[0], chan.2);
6058
6059         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6060         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6061         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1);
6062         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6063         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();
6064
6065         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6066         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6067         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6068         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6069
6070         // Flush the pending fee update.
6071         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6072         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6073         check_added_monitors!(nodes[1], 1);
6074         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6075         check_added_monitors!(nodes[0], 1);
6076
6077         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6078         // HTLC, but now that the fee has been raised the payment will now fail, causing
6079         // us to surface its failure to the user.
6080         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6081         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6082         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 1 HTLC updates".to_string(), 1);
6083         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);
6084         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6085
6086         // Check that the payment failed to be sent out.
6087         let events = nodes[0].node.get_and_clear_pending_events();
6088         assert_eq!(events.len(), 1);
6089         match &events[0] {
6090                 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6091                         assert_eq!(our_payment_hash.clone(), *payment_hash);
6092                         assert_eq!(*rejected_by_dest, false);
6093                         assert_eq!(*error_code, None);
6094                         assert_eq!(*error_data, None);
6095                 },
6096                 _ => panic!("Unexpected event"),
6097         }
6098 }
6099
6100 // Test that if multiple HTLCs are released from the holding cell and one is
6101 // valid but the other is no longer valid upon release, the valid HTLC can be
6102 // successfully completed while the other one fails as expected.
6103 #[test]
6104 fn test_free_and_fail_holding_cell_htlcs() {
6105         let chanmon_cfgs = create_chanmon_cfgs(2);
6106         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6107         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6108         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6109         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6110         let logger = test_utils::TestLogger::new();
6111
6112         // First nodes[0] generates an update_fee, setting the channel's
6113         // pending_update_fee.
6114         nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 200).unwrap();
6115         check_added_monitors!(nodes[0], 1);
6116
6117         let events = nodes[0].node.get_and_clear_pending_msg_events();
6118         assert_eq!(events.len(), 1);
6119         let (update_msg, commitment_signed) = match events[0] {
6120                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6121                         (update_fee.as_ref(), commitment_signed)
6122                 },
6123                 _ => panic!("Unexpected event"),
6124         };
6125
6126         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6127
6128         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6129         let channel_reserve = chan_stat.channel_reserve_msat;
6130         let feerate = get_feerate!(nodes[0], chan.2);
6131
6132         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6133         let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
6134         let amt_1 = 20000;
6135         let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
6136         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1) - amt_1;
6137         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6138         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();
6139         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();
6140
6141         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6142         nodes[0].node.send_payment(&route_1, payment_hash_1, &None).unwrap();
6143         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6144         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6145         nodes[0].node.send_payment(&route_2, payment_hash_2, &None).unwrap();
6146         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6147         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6148
6149         // Flush the pending fee update.
6150         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6151         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6152         check_added_monitors!(nodes[1], 1);
6153         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6154         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6155         check_added_monitors!(nodes[0], 2);
6156
6157         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6158         // but now that the fee has been raised the second payment will now fail, causing us
6159         // to surface its failure to the user. The first payment should succeed.
6160         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6161         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6162         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 2 HTLC updates".to_string(), 1);
6163         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);
6164         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6165
6166         // Check that the second payment failed to be sent out.
6167         let events = nodes[0].node.get_and_clear_pending_events();
6168         assert_eq!(events.len(), 1);
6169         match &events[0] {
6170                 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6171                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6172                         assert_eq!(*rejected_by_dest, false);
6173                         assert_eq!(*error_code, None);
6174                         assert_eq!(*error_data, None);
6175                 },
6176                 _ => panic!("Unexpected event"),
6177         }
6178
6179         // Complete the first payment and the RAA from the fee update.
6180         let (payment_event, send_raa_event) = {
6181                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6182                 assert_eq!(msgs.len(), 2);
6183                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6184         };
6185         let raa = match send_raa_event {
6186                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6187                 _ => panic!("Unexpected event"),
6188         };
6189         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6190         check_added_monitors!(nodes[1], 1);
6191         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6192         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6193         let events = nodes[1].node.get_and_clear_pending_events();
6194         assert_eq!(events.len(), 1);
6195         match events[0] {
6196                 Event::PendingHTLCsForwardable { .. } => {},
6197                 _ => panic!("Unexpected event"),
6198         }
6199         nodes[1].node.process_pending_htlc_forwards();
6200         let events = nodes[1].node.get_and_clear_pending_events();
6201         assert_eq!(events.len(), 1);
6202         match events[0] {
6203                 Event::PaymentReceived { .. } => {},
6204                 _ => panic!("Unexpected event"),
6205         }
6206         nodes[1].node.claim_funds(payment_preimage_1, &None, amt_1);
6207         check_added_monitors!(nodes[1], 1);
6208         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6209         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6210         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6211         let events = nodes[0].node.get_and_clear_pending_events();
6212         assert_eq!(events.len(), 1);
6213         match events[0] {
6214                 Event::PaymentSent { ref payment_preimage } => {
6215                         assert_eq!(*payment_preimage, payment_preimage_1);
6216                 }
6217                 _ => panic!("Unexpected event"),
6218         }
6219 }
6220
6221 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6222 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6223 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6224 // once it's freed.
6225 #[test]
6226 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6227         let chanmon_cfgs = create_chanmon_cfgs(3);
6228         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6229         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6230         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6231         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6232         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6233         let logger = test_utils::TestLogger::new();
6234
6235         // First nodes[1] generates an update_fee, setting the channel's
6236         // pending_update_fee.
6237         nodes[1].node.update_fee(chan_1_2.2, get_feerate!(nodes[1], chan_1_2.2) + 20).unwrap();
6238         check_added_monitors!(nodes[1], 1);
6239
6240         let events = nodes[1].node.get_and_clear_pending_msg_events();
6241         assert_eq!(events.len(), 1);
6242         let (update_msg, commitment_signed) = match events[0] {
6243                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6244                         (update_fee.as_ref(), commitment_signed)
6245                 },
6246                 _ => panic!("Unexpected event"),
6247         };
6248
6249         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6250
6251         let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6252         let channel_reserve = chan_stat.channel_reserve_msat;
6253         let feerate = get_feerate!(nodes[0], chan_0_1.2);
6254
6255         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6256         let feemsat = 239;
6257         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6258         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6259         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1) - total_routing_fee_msat;
6260         let payment_event = {
6261                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6262                 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();
6263                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6264                 check_added_monitors!(nodes[0], 1);
6265
6266                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6267                 assert_eq!(events.len(), 1);
6268
6269                 SendEvent::from_event(events.remove(0))
6270         };
6271         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6272         check_added_monitors!(nodes[1], 0);
6273         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6274         expect_pending_htlcs_forwardable!(nodes[1]);
6275
6276         chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6277         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6278
6279         // Flush the pending fee update.
6280         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6281         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6282         check_added_monitors!(nodes[2], 1);
6283         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6284         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6285         check_added_monitors!(nodes[1], 2);
6286
6287         // A final RAA message is generated to finalize the fee update.
6288         let events = nodes[1].node.get_and_clear_pending_msg_events();
6289         assert_eq!(events.len(), 1);
6290
6291         let raa_msg = match &events[0] {
6292                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6293                         msg.clone()
6294                 },
6295                 _ => panic!("Unexpected event"),
6296         };
6297
6298         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6299         check_added_monitors!(nodes[2], 1);
6300         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6301
6302         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6303         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6304         assert_eq!(process_htlc_forwards_event.len(), 1);
6305         match &process_htlc_forwards_event[0] {
6306                 &Event::PendingHTLCsForwardable { .. } => {},
6307                 _ => panic!("Unexpected event"),
6308         }
6309
6310         // In response, we call ChannelManager's process_pending_htlc_forwards
6311         nodes[1].node.process_pending_htlc_forwards();
6312         check_added_monitors!(nodes[1], 1);
6313
6314         // This causes the HTLC to be failed backwards.
6315         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6316         assert_eq!(fail_event.len(), 1);
6317         let (fail_msg, commitment_signed) = match &fail_event[0] {
6318                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6319                         assert_eq!(updates.update_add_htlcs.len(), 0);
6320                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6321                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6322                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6323                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6324                 },
6325                 _ => panic!("Unexpected event"),
6326         };
6327
6328         // Pass the failure messages back to nodes[0].
6329         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6330         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6331
6332         // Complete the HTLC failure+removal process.
6333         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6334         check_added_monitors!(nodes[0], 1);
6335         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6336         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6337         check_added_monitors!(nodes[1], 2);
6338         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6339         assert_eq!(final_raa_event.len(), 1);
6340         let raa = match &final_raa_event[0] {
6341                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6342                 _ => panic!("Unexpected event"),
6343         };
6344         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6345         let fail_msg_event = nodes[0].node.get_and_clear_pending_msg_events();
6346         assert_eq!(fail_msg_event.len(), 1);
6347         match &fail_msg_event[0] {
6348                 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6349                 _ => panic!("Unexpected event"),
6350         }
6351         let failure_event = nodes[0].node.get_and_clear_pending_events();
6352         assert_eq!(failure_event.len(), 1);
6353         match &failure_event[0] {
6354                 &Event::PaymentFailed { rejected_by_dest, .. } => {
6355                         assert!(!rejected_by_dest);
6356                 },
6357                 _ => panic!("Unexpected event"),
6358         }
6359         check_added_monitors!(nodes[0], 1);
6360 }
6361
6362 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6363 // 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.
6364 //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.
6365
6366 #[test]
6367 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6368         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6369         let chanmon_cfgs = create_chanmon_cfgs(2);
6370         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6371         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6372         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6373         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6374
6375         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6376         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6377         let logger = test_utils::TestLogger::new();
6378         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();
6379         route.paths[0][0].fee_msat = 100;
6380
6381         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6382                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6383         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6384         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6385 }
6386
6387 #[test]
6388 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6389         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6390         let chanmon_cfgs = create_chanmon_cfgs(2);
6391         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6392         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6393         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6394         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6395         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6396
6397         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6398         let logger = test_utils::TestLogger::new();
6399         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();
6400         route.paths[0][0].fee_msat = 0;
6401         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6402                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6403
6404         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6405         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6406 }
6407
6408 #[test]
6409 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6410         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6411         let chanmon_cfgs = create_chanmon_cfgs(2);
6412         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6413         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6414         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6415         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6416
6417         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6418         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6419         let logger = test_utils::TestLogger::new();
6420         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();
6421         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6422         check_added_monitors!(nodes[0], 1);
6423         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6424         updates.update_add_htlcs[0].amount_msat = 0;
6425
6426         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6427         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6428         check_closed_broadcast!(nodes[1], true).unwrap();
6429         check_added_monitors!(nodes[1], 1);
6430 }
6431
6432 #[test]
6433 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6434         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6435         //It is enforced when constructing a route.
6436         let chanmon_cfgs = create_chanmon_cfgs(2);
6437         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6438         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6439         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6440         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 0, InitFeatures::known(), InitFeatures::known());
6441         let logger = test_utils::TestLogger::new();
6442
6443         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6444
6445         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6446         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();
6447         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::RouteError { ref err },
6448                 assert_eq!(err, &"Channel CLTV overflowed?"));
6449 }
6450
6451 #[test]
6452 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6453         //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.
6454         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6455         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6456         let chanmon_cfgs = create_chanmon_cfgs(2);
6457         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6458         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6459         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6460         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6461         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6462
6463         let logger = test_utils::TestLogger::new();
6464         for i in 0..max_accepted_htlcs {
6465                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6466                 let payment_event = {
6467                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6468                         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();
6469                         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6470                         check_added_monitors!(nodes[0], 1);
6471
6472                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6473                         assert_eq!(events.len(), 1);
6474                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6475                                 assert_eq!(htlcs[0].htlc_id, i);
6476                         } else {
6477                                 assert!(false);
6478                         }
6479                         SendEvent::from_event(events.remove(0))
6480                 };
6481                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6482                 check_added_monitors!(nodes[1], 0);
6483                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6484
6485                 expect_pending_htlcs_forwardable!(nodes[1]);
6486                 expect_payment_received!(nodes[1], our_payment_hash, 100000);
6487         }
6488         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6489         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6490         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();
6491         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6492                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6493
6494         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6495         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6496 }
6497
6498 #[test]
6499 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6500         //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.
6501         let chanmon_cfgs = create_chanmon_cfgs(2);
6502         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6503         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6504         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6505         let channel_value = 100000;
6506         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6507         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6508
6509         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight, max_in_flight);
6510
6511         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6512         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6513         let logger = test_utils::TestLogger::new();
6514         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();
6515         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6516                 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)));
6517
6518         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6519         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);
6520
6521         send_payment(&nodes[0], &[&nodes[1]], max_in_flight, max_in_flight);
6522 }
6523
6524 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6525 #[test]
6526 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6527         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6528         let chanmon_cfgs = create_chanmon_cfgs(2);
6529         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6530         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6531         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6532         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6533         let htlc_minimum_msat: u64;
6534         {
6535                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6536                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6537                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6538         }
6539
6540         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6541         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6542         let logger = test_utils::TestLogger::new();
6543         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();
6544         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6545         check_added_monitors!(nodes[0], 1);
6546         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6547         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6548         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6549         assert!(nodes[1].node.list_channels().is_empty());
6550         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6551         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()));
6552         check_added_monitors!(nodes[1], 1);
6553 }
6554
6555 #[test]
6556 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6557         //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
6558         let chanmon_cfgs = create_chanmon_cfgs(2);
6559         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6560         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6561         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6562         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6563         let logger = test_utils::TestLogger::new();
6564
6565         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6566         let channel_reserve = chan_stat.channel_reserve_msat;
6567         let feerate = get_feerate!(nodes[0], chan.2);
6568         // The 2* and +1 are for the fee spike reserve.
6569         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1);
6570
6571         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6572         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6573         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6574         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();
6575         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6576         check_added_monitors!(nodes[0], 1);
6577         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6578
6579         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6580         // at this time channel-initiatee receivers are not required to enforce that senders
6581         // respect the fee_spike_reserve.
6582         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6583         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6584
6585         assert!(nodes[1].node.list_channels().is_empty());
6586         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6587         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6588         check_added_monitors!(nodes[1], 1);
6589 }
6590
6591 #[test]
6592 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6593         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6594         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6595         let chanmon_cfgs = create_chanmon_cfgs(2);
6596         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6597         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6598         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6599         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6600         let logger = test_utils::TestLogger::new();
6601
6602         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6603         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6604
6605         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6606         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();
6607
6608         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
6609         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6610         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &None, cur_height).unwrap();
6611         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6612
6613         let mut msg = msgs::UpdateAddHTLC {
6614                 channel_id: chan.2,
6615                 htlc_id: 0,
6616                 amount_msat: 1000,
6617                 payment_hash: our_payment_hash,
6618                 cltv_expiry: htlc_cltv,
6619                 onion_routing_packet: onion_packet.clone(),
6620         };
6621
6622         for i in 0..super::channel::OUR_MAX_HTLCS {
6623                 msg.htlc_id = i as u64;
6624                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6625         }
6626         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6627         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6628
6629         assert!(nodes[1].node.list_channels().is_empty());
6630         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6631         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6632         check_added_monitors!(nodes[1], 1);
6633 }
6634
6635 #[test]
6636 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6637         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6638         let chanmon_cfgs = create_chanmon_cfgs(2);
6639         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6640         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6641         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6642         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6643         let logger = test_utils::TestLogger::new();
6644
6645         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6646         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6647         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();
6648         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6649         check_added_monitors!(nodes[0], 1);
6650         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6651         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6652         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6653
6654         assert!(nodes[1].node.list_channels().is_empty());
6655         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6656         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6657         check_added_monitors!(nodes[1], 1);
6658 }
6659
6660 #[test]
6661 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6662         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6663         let chanmon_cfgs = create_chanmon_cfgs(2);
6664         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6665         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6666         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6667         let logger = test_utils::TestLogger::new();
6668
6669         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6670         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6671         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6672         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();
6673         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6674         check_added_monitors!(nodes[0], 1);
6675         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6676         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6677         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6678
6679         assert!(nodes[1].node.list_channels().is_empty());
6680         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6681         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6682         check_added_monitors!(nodes[1], 1);
6683 }
6684
6685 #[test]
6686 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6687         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6688         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6689         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6690         let chanmon_cfgs = create_chanmon_cfgs(2);
6691         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6692         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6693         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6694         let logger = test_utils::TestLogger::new();
6695
6696         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6697         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6698         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6699         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();
6700         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6701         check_added_monitors!(nodes[0], 1);
6702         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6703         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6704
6705         //Disconnect and Reconnect
6706         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6707         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6708         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6709         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6710         assert_eq!(reestablish_1.len(), 1);
6711         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6712         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6713         assert_eq!(reestablish_2.len(), 1);
6714         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6715         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6716         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6717         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6718
6719         //Resend HTLC
6720         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6721         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6722         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6723         check_added_monitors!(nodes[1], 1);
6724         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6725
6726         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6727
6728         assert!(nodes[1].node.list_channels().is_empty());
6729         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6730         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6731         check_added_monitors!(nodes[1], 1);
6732 }
6733
6734 #[test]
6735 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6736         //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.
6737
6738         let chanmon_cfgs = create_chanmon_cfgs(2);
6739         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6740         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6741         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6742         let logger = test_utils::TestLogger::new();
6743         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6744         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6745         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6746         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();
6747         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6748
6749         check_added_monitors!(nodes[0], 1);
6750         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6751         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6752
6753         let update_msg = msgs::UpdateFulfillHTLC{
6754                 channel_id: chan.2,
6755                 htlc_id: 0,
6756                 payment_preimage: our_payment_preimage,
6757         };
6758
6759         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6760
6761         assert!(nodes[0].node.list_channels().is_empty());
6762         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6763         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()));
6764         check_added_monitors!(nodes[0], 1);
6765 }
6766
6767 #[test]
6768 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6769         //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.
6770
6771         let chanmon_cfgs = create_chanmon_cfgs(2);
6772         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6773         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6774         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6775         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6776         let logger = test_utils::TestLogger::new();
6777
6778         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6779         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6780         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();
6781         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6782         check_added_monitors!(nodes[0], 1);
6783         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6784         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6785
6786         let update_msg = msgs::UpdateFailHTLC{
6787                 channel_id: chan.2,
6788                 htlc_id: 0,
6789                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6790         };
6791
6792         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6793
6794         assert!(nodes[0].node.list_channels().is_empty());
6795         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6796         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()));
6797         check_added_monitors!(nodes[0], 1);
6798 }
6799
6800 #[test]
6801 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6802         //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.
6803
6804         let chanmon_cfgs = create_chanmon_cfgs(2);
6805         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6806         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6807         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6808         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6809         let logger = test_utils::TestLogger::new();
6810
6811         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6812         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6813         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();
6814         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6815         check_added_monitors!(nodes[0], 1);
6816         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6817         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6818
6819         let update_msg = msgs::UpdateFailMalformedHTLC{
6820                 channel_id: chan.2,
6821                 htlc_id: 0,
6822                 sha256_of_onion: [1; 32],
6823                 failure_code: 0x8000,
6824         };
6825
6826         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6827
6828         assert!(nodes[0].node.list_channels().is_empty());
6829         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6830         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()));
6831         check_added_monitors!(nodes[0], 1);
6832 }
6833
6834 #[test]
6835 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6836         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6837
6838         let chanmon_cfgs = create_chanmon_cfgs(2);
6839         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6840         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6841         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6842         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6843
6844         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6845
6846         nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6847         check_added_monitors!(nodes[1], 1);
6848
6849         let events = nodes[1].node.get_and_clear_pending_msg_events();
6850         assert_eq!(events.len(), 1);
6851         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6852                 match events[0] {
6853                         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, .. } } => {
6854                                 assert!(update_add_htlcs.is_empty());
6855                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6856                                 assert!(update_fail_htlcs.is_empty());
6857                                 assert!(update_fail_malformed_htlcs.is_empty());
6858                                 assert!(update_fee.is_none());
6859                                 update_fulfill_htlcs[0].clone()
6860                         },
6861                         _ => panic!("Unexpected event"),
6862                 }
6863         };
6864
6865         update_fulfill_msg.htlc_id = 1;
6866
6867         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6868
6869         assert!(nodes[0].node.list_channels().is_empty());
6870         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6871         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6872         check_added_monitors!(nodes[0], 1);
6873 }
6874
6875 #[test]
6876 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6877         //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.
6878
6879         let chanmon_cfgs = create_chanmon_cfgs(2);
6880         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6881         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6882         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6883         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6884
6885         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6886
6887         nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6888         check_added_monitors!(nodes[1], 1);
6889
6890         let events = nodes[1].node.get_and_clear_pending_msg_events();
6891         assert_eq!(events.len(), 1);
6892         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6893                 match events[0] {
6894                         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, .. } } => {
6895                                 assert!(update_add_htlcs.is_empty());
6896                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6897                                 assert!(update_fail_htlcs.is_empty());
6898                                 assert!(update_fail_malformed_htlcs.is_empty());
6899                                 assert!(update_fee.is_none());
6900                                 update_fulfill_htlcs[0].clone()
6901                         },
6902                         _ => panic!("Unexpected event"),
6903                 }
6904         };
6905
6906         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6907
6908         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6909
6910         assert!(nodes[0].node.list_channels().is_empty());
6911         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6912         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6913         check_added_monitors!(nodes[0], 1);
6914 }
6915
6916 #[test]
6917 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6918         //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.
6919
6920         let chanmon_cfgs = create_chanmon_cfgs(2);
6921         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6922         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6923         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6924         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6925         let logger = test_utils::TestLogger::new();
6926
6927         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6928         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6929         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();
6930         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6931         check_added_monitors!(nodes[0], 1);
6932
6933         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6934         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6935
6936         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6937         check_added_monitors!(nodes[1], 0);
6938         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6939
6940         let events = nodes[1].node.get_and_clear_pending_msg_events();
6941
6942         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6943                 match events[0] {
6944                         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, .. } } => {
6945                                 assert!(update_add_htlcs.is_empty());
6946                                 assert!(update_fulfill_htlcs.is_empty());
6947                                 assert!(update_fail_htlcs.is_empty());
6948                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6949                                 assert!(update_fee.is_none());
6950                                 update_fail_malformed_htlcs[0].clone()
6951                         },
6952                         _ => panic!("Unexpected event"),
6953                 }
6954         };
6955         update_msg.failure_code &= !0x8000;
6956         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6957
6958         assert!(nodes[0].node.list_channels().is_empty());
6959         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6960         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6961         check_added_monitors!(nodes[0], 1);
6962 }
6963
6964 #[test]
6965 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6966         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6967         //    * 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.
6968
6969         let chanmon_cfgs = create_chanmon_cfgs(3);
6970         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6971         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6972         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6973         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6974         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6975         let logger = test_utils::TestLogger::new();
6976
6977         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6978
6979         //First hop
6980         let mut payment_event = {
6981                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6982                 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();
6983                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6984                 check_added_monitors!(nodes[0], 1);
6985                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6986                 assert_eq!(events.len(), 1);
6987                 SendEvent::from_event(events.remove(0))
6988         };
6989         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6990         check_added_monitors!(nodes[1], 0);
6991         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6992         expect_pending_htlcs_forwardable!(nodes[1]);
6993         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6994         assert_eq!(events_2.len(), 1);
6995         check_added_monitors!(nodes[1], 1);
6996         payment_event = SendEvent::from_event(events_2.remove(0));
6997         assert_eq!(payment_event.msgs.len(), 1);
6998
6999         //Second Hop
7000         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7001         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7002         check_added_monitors!(nodes[2], 0);
7003         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7004
7005         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7006         assert_eq!(events_3.len(), 1);
7007         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
7008                 match events_3[0] {
7009                         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 } } => {
7010                                 assert!(update_add_htlcs.is_empty());
7011                                 assert!(update_fulfill_htlcs.is_empty());
7012                                 assert!(update_fail_htlcs.is_empty());
7013                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7014                                 assert!(update_fee.is_none());
7015                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
7016                         },
7017                         _ => panic!("Unexpected event"),
7018                 }
7019         };
7020
7021         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
7022
7023         check_added_monitors!(nodes[1], 0);
7024         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
7025         expect_pending_htlcs_forwardable!(nodes[1]);
7026         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7027         assert_eq!(events_4.len(), 1);
7028
7029         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7030         match events_4[0] {
7031                 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, .. } } => {
7032                         assert!(update_add_htlcs.is_empty());
7033                         assert!(update_fulfill_htlcs.is_empty());
7034                         assert_eq!(update_fail_htlcs.len(), 1);
7035                         assert!(update_fail_malformed_htlcs.is_empty());
7036                         assert!(update_fee.is_none());
7037                 },
7038                 _ => panic!("Unexpected event"),
7039         };
7040
7041         check_added_monitors!(nodes[1], 1);
7042 }
7043
7044 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7045         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7046         // 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
7047         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7048
7049         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7050         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7051         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7052         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7053         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7054         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7055
7056         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7057
7058         // We route 2 dust-HTLCs between A and B
7059         let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7060         let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7061         route_payment(&nodes[0], &[&nodes[1]], 1000000);
7062
7063         // Cache one local commitment tx as previous
7064         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7065
7066         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7067         assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2, &None));
7068         check_added_monitors!(nodes[1], 0);
7069         expect_pending_htlcs_forwardable!(nodes[1]);
7070         check_added_monitors!(nodes[1], 1);
7071
7072         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7073         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7074         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7075         check_added_monitors!(nodes[0], 1);
7076
7077         // Cache one local commitment tx as lastest
7078         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7079
7080         let events = nodes[0].node.get_and_clear_pending_msg_events();
7081         match events[0] {
7082                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7083                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7084                 },
7085                 _ => panic!("Unexpected event"),
7086         }
7087         match events[1] {
7088                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7089                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7090                 },
7091                 _ => panic!("Unexpected event"),
7092         }
7093
7094         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7095         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7096         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7097
7098         if announce_latest {
7099                 connect_block(&nodes[0], &Block { header, txdata: vec![as_last_commitment_tx[0].clone()]}, 1);
7100         } else {
7101                 connect_block(&nodes[0], &Block { header, txdata: vec![as_prev_commitment_tx[0].clone()]}, 1);
7102         }
7103
7104         check_closed_broadcast!(nodes[0], false);
7105         check_added_monitors!(nodes[0], 1);
7106
7107         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7108         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 1, true,  header.block_hash());
7109         let events = nodes[0].node.get_and_clear_pending_events();
7110         // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
7111         assert_eq!(events.len(), 2);
7112         let mut first_failed = false;
7113         for event in events {
7114                 match event {
7115                         Event::PaymentFailed { payment_hash, .. } => {
7116                                 if payment_hash == payment_hash_1 {
7117                                         assert!(!first_failed);
7118                                         first_failed = true;
7119                                 } else {
7120                                         assert_eq!(payment_hash, payment_hash_2);
7121                                 }
7122                         }
7123                         _ => panic!("Unexpected event"),
7124                 }
7125         }
7126 }
7127
7128 #[test]
7129 fn test_failure_delay_dust_htlc_local_commitment() {
7130         do_test_failure_delay_dust_htlc_local_commitment(true);
7131         do_test_failure_delay_dust_htlc_local_commitment(false);
7132 }
7133
7134 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7135         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7136         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7137         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7138         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7139         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7140         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7141
7142         let chanmon_cfgs = create_chanmon_cfgs(3);
7143         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7144         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7145         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7146         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7147
7148         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7149
7150         let (_payment_preimage_1, dust_hash) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7151         let (_payment_preimage_2, non_dust_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7152
7153         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7154         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7155
7156         // We revoked bs_commitment_tx
7157         if revoked {
7158                 let (payment_preimage_3, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7159                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 1_000_000);
7160         }
7161
7162         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7163         let mut timeout_tx = Vec::new();
7164         if local {
7165                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7166                 connect_block(&nodes[0], &Block { header, txdata: vec![as_commitment_tx[0].clone()]}, 1);
7167                 check_closed_broadcast!(nodes[0], false);
7168                 check_added_monitors!(nodes[0], 1);
7169                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7170                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7171                 let parent_hash  = connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 2, true, header.block_hash());
7172                 expect_payment_failed!(nodes[0], dust_hash, true);
7173                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7174                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7175                 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7176                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7177                 connect_block(&nodes[0], &Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
7178                 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7179                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 8, true, header_3.block_hash());
7180                 expect_payment_failed!(nodes[0], non_dust_hash, true);
7181         } else {
7182                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7183                 connect_block(&nodes[0], &Block { header, txdata: vec![bs_commitment_tx[0].clone()]}, 1);
7184                 check_closed_broadcast!(nodes[0], false);
7185                 check_added_monitors!(nodes[0], 1);
7186                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7187                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7188                 let parent_hash  = connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 2, true, header.block_hash());
7189                 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7190                 if !revoked {
7191                         expect_payment_failed!(nodes[0], dust_hash, true);
7192                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7193                         // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7194                         connect_block(&nodes[0], &Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
7195                         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7196                         let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7197                         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 8, true, header_3.block_hash());
7198                         expect_payment_failed!(nodes[0], non_dust_hash, true);
7199                 } else {
7200                         // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7201                         // commitment tx
7202                         let events = nodes[0].node.get_and_clear_pending_events();
7203                         assert_eq!(events.len(), 2);
7204                         let first;
7205                         match events[0] {
7206                                 Event::PaymentFailed { payment_hash, .. } => {
7207                                         if payment_hash == dust_hash { first = true; }
7208                                         else { first = false; }
7209                                 },
7210                                 _ => panic!("Unexpected event"),
7211                         }
7212                         match events[1] {
7213                                 Event::PaymentFailed { payment_hash, .. } => {
7214                                         if first { assert_eq!(payment_hash, non_dust_hash); }
7215                                         else { assert_eq!(payment_hash, dust_hash); }
7216                                 },
7217                                 _ => panic!("Unexpected event"),
7218                         }
7219                 }
7220         }
7221 }
7222
7223 #[test]
7224 fn test_sweep_outbound_htlc_failure_update() {
7225         do_test_sweep_outbound_htlc_failure_update(false, true);
7226         do_test_sweep_outbound_htlc_failure_update(false, false);
7227         do_test_sweep_outbound_htlc_failure_update(true, false);
7228 }
7229
7230 #[test]
7231 fn test_upfront_shutdown_script() {
7232         // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
7233         // enforce it at shutdown message
7234
7235         let mut config = UserConfig::default();
7236         config.channel_options.announced_channel = true;
7237         config.peer_channel_config_limits.force_announced_channel_preference = false;
7238         config.channel_options.commit_upfront_shutdown_pubkey = false;
7239         let user_cfgs = [None, Some(config), None];
7240         let chanmon_cfgs = create_chanmon_cfgs(3);
7241         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7242         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7243         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7244
7245         // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
7246         let flags = InitFeatures::known();
7247         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7248         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7249         let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7250         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7251         // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that  we disconnect peer
7252         nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
7253     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()));
7254         check_added_monitors!(nodes[2], 1);
7255
7256         // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
7257         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7258         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7259         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7260         // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
7261         nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
7262         let events = nodes[2].node.get_and_clear_pending_msg_events();
7263         assert_eq!(events.len(), 1);
7264         match events[0] {
7265                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7266                 _ => panic!("Unexpected event"),
7267         }
7268
7269         // We test that if case of peer non-signaling we don't enforce committed script at channel opening
7270         let flags_no = InitFeatures::known().clear_upfront_shutdown_script();
7271         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone());
7272         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7273         let mut node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
7274         node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7275         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_1_shutdown);
7276         let events = nodes[1].node.get_and_clear_pending_msg_events();
7277         assert_eq!(events.len(), 1);
7278         match events[0] {
7279                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7280                 _ => panic!("Unexpected event"),
7281         }
7282
7283         // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7284         // channel smoothly, opt-out is from channel initiator here
7285         let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone());
7286         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7287         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7288         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7289         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
7290         let events = nodes[0].node.get_and_clear_pending_msg_events();
7291         assert_eq!(events.len(), 1);
7292         match events[0] {
7293                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7294                 _ => panic!("Unexpected event"),
7295         }
7296
7297         //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7298         //// channel smoothly
7299         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone());
7300         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7301         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7302         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7303         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
7304         let events = nodes[0].node.get_and_clear_pending_msg_events();
7305         assert_eq!(events.len(), 2);
7306         match events[0] {
7307                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7308                 _ => panic!("Unexpected event"),
7309         }
7310         match events[1] {
7311                 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7312                 _ => panic!("Unexpected event"),
7313         }
7314 }
7315
7316 #[test]
7317 fn test_user_configurable_csv_delay() {
7318         // We test our channel constructors yield errors when we pass them absurd csv delay
7319
7320         let mut low_our_to_self_config = UserConfig::default();
7321         low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7322         let mut high_their_to_self_config = UserConfig::default();
7323         high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7324         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7325         let chanmon_cfgs = create_chanmon_cfgs(2);
7326         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7327         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7328         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7329
7330         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7331         if let Err(error) = Channel::new_outbound(&&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), 1000000, 1000000, 0, &low_our_to_self_config) {
7332                 match error {
7333                         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())); },
7334                         _ => panic!("Unexpected event"),
7335                 }
7336         } else { assert!(false) }
7337
7338         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7339         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7340         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7341         open_channel.to_self_delay = 200;
7342         if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel, 0, &low_our_to_self_config) {
7343                 match error {
7344                         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()));  },
7345                         _ => panic!("Unexpected event"),
7346                 }
7347         } else { assert!(false); }
7348
7349         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7350         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7351         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()));
7352         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7353         accept_channel.to_self_delay = 200;
7354         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7355         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7356                 match action {
7357                         &ErrorAction::SendErrorMessage { ref msg } => {
7358                                 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()));
7359                         },
7360                         _ => { assert!(false); }
7361                 }
7362         } else { assert!(false); }
7363
7364         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7365         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7366         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7367         open_channel.to_self_delay = 200;
7368         if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel, 0, &high_their_to_self_config) {
7369                 match error {
7370                         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())); },
7371                         _ => panic!("Unexpected event"),
7372                 }
7373         } else { assert!(false); }
7374 }
7375
7376 #[test]
7377 fn test_data_loss_protect() {
7378         // We want to be sure that :
7379         // * we don't broadcast our Local Commitment Tx in case of fallen behind
7380         //   (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7381         // * we close channel in case of detecting other being fallen behind
7382         // * we are able to claim our own outputs thanks to to_remote being static
7383         // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7384         let persister;
7385         let logger;
7386         let fee_estimator;
7387         let tx_broadcaster;
7388         let chain_source;
7389         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7390         // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7391         // during signing due to revoked tx
7392         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7393         let keys_manager = &chanmon_cfgs[0].keys_manager;
7394         let monitor;
7395         let node_state_0;
7396         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7397         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7398         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7399
7400         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7401
7402         // Cache node A state before any channel update
7403         let previous_node_state = nodes[0].node.encode();
7404         let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7405         nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write(&mut previous_chain_monitor_state).unwrap();
7406
7407         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7408         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7409
7410         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7411         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7412
7413         // Restore node A from previous state
7414         logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7415         let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut ::std::io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7416         chain_source = test_utils::TestChainSource::new(Network::Testnet);
7417         tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
7418         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
7419         persister = test_utils::TestPersister::new();
7420         monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7421         node_state_0 = {
7422                 let mut channel_monitors = HashMap::new();
7423                 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7424                 <(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 {
7425                         keys_manager: keys_manager,
7426                         fee_estimator: &fee_estimator,
7427                         chain_monitor: &monitor,
7428                         logger: &logger,
7429                         tx_broadcaster: &tx_broadcaster,
7430                         default_config: UserConfig::default(),
7431                         channel_monitors,
7432                 }).unwrap().1
7433         };
7434         nodes[0].node = &node_state_0;
7435         assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7436         nodes[0].chain_monitor = &monitor;
7437         nodes[0].chain_source = &chain_source;
7438
7439         check_added_monitors!(nodes[0], 1);
7440
7441         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7442         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7443
7444         let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7445
7446         // Check we don't broadcast any transactions following learning of per_commitment_point from B
7447         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7448         check_added_monitors!(nodes[0], 1);
7449
7450         {
7451                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7452                 assert_eq!(node_txn.len(), 0);
7453         }
7454
7455         let mut reestablish_1 = Vec::with_capacity(1);
7456         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7457                 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7458                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7459                         reestablish_1.push(msg.clone());
7460                 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7461                 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7462                         match action {
7463                                 &ErrorAction::SendErrorMessage { ref msg } => {
7464                                         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");
7465                                 },
7466                                 _ => panic!("Unexpected event!"),
7467                         }
7468                 } else {
7469                         panic!("Unexpected event")
7470                 }
7471         }
7472
7473         // Check we close channel detecting A is fallen-behind
7474         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7475         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7476         check_added_monitors!(nodes[1], 1);
7477
7478
7479         // Check A is able to claim to_remote output
7480         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7481         assert_eq!(node_txn.len(), 1);
7482         check_spends!(node_txn[0], chan.3);
7483         assert_eq!(node_txn[0].output.len(), 2);
7484         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
7485         connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[0].clone()]}, 0);
7486         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
7487         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
7488         assert_eq!(spend_txn.len(), 1);
7489         check_spends!(spend_txn[0], node_txn[0]);
7490 }
7491
7492 #[test]
7493 fn test_check_htlc_underpaying() {
7494         // Send payment through A -> B but A is maliciously
7495         // sending a probe payment (i.e less than expected value0
7496         // to B, B should refuse payment.
7497
7498         let chanmon_cfgs = create_chanmon_cfgs(2);
7499         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7500         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7501         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7502
7503         // Create some initial channels
7504         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7505
7506         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 10_000);
7507
7508         // Node 3 is expecting payment of 100_000 but receive 10_000,
7509         // fail htlc like we didn't know the preimage.
7510         nodes[1].node.claim_funds(payment_preimage, &None, 100_000);
7511         nodes[1].node.process_pending_htlc_forwards();
7512
7513         let events = nodes[1].node.get_and_clear_pending_msg_events();
7514         assert_eq!(events.len(), 1);
7515         let (update_fail_htlc, commitment_signed) = match events[0] {
7516                 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 } } => {
7517                         assert!(update_add_htlcs.is_empty());
7518                         assert!(update_fulfill_htlcs.is_empty());
7519                         assert_eq!(update_fail_htlcs.len(), 1);
7520                         assert!(update_fail_malformed_htlcs.is_empty());
7521                         assert!(update_fee.is_none());
7522                         (update_fail_htlcs[0].clone(), commitment_signed)
7523                 },
7524                 _ => panic!("Unexpected event"),
7525         };
7526         check_added_monitors!(nodes[1], 1);
7527
7528         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7529         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7530
7531         // 10_000 msat as u64, followed by a height of 99 as u32
7532         let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7533         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(99));
7534         expect_payment_failed!(nodes[0], payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7535         nodes[1].node.get_and_clear_pending_events();
7536 }
7537
7538 #[test]
7539 fn test_announce_disable_channels() {
7540         // Create 2 channels between A and B. Disconnect B. Call timer_chan_freshness_every_min and check for generated
7541         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7542
7543         let chanmon_cfgs = create_chanmon_cfgs(2);
7544         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7545         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7546         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7547
7548         let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7549         let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7550         let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7551
7552         // Disconnect peers
7553         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7554         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7555
7556         nodes[0].node.timer_chan_freshness_every_min(); // dirty -> stagged
7557         nodes[0].node.timer_chan_freshness_every_min(); // staged -> fresh
7558         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7559         assert_eq!(msg_events.len(), 3);
7560         for e in msg_events {
7561                 match e {
7562                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7563                                 let short_id = msg.contents.short_channel_id;
7564                                 // Check generated channel_update match list in PendingChannelUpdate
7565                                 if short_id != short_id_1 && short_id != short_id_2 && short_id != short_id_3 {
7566                                         panic!("Generated ChannelUpdate for wrong chan!");
7567                                 }
7568                         },
7569                         _ => panic!("Unexpected event"),
7570                 }
7571         }
7572         // Reconnect peers
7573         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7574         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7575         assert_eq!(reestablish_1.len(), 3);
7576         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7577         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7578         assert_eq!(reestablish_2.len(), 3);
7579
7580         // Reestablish chan_1
7581         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7582         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7583         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7584         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7585         // Reestablish chan_2
7586         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7587         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7588         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7589         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7590         // Reestablish chan_3
7591         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7592         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7593         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7594         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7595
7596         nodes[0].node.timer_chan_freshness_every_min();
7597         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7598 }
7599
7600 #[test]
7601 fn test_bump_penalty_txn_on_revoked_commitment() {
7602         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7603         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7604
7605         let chanmon_cfgs = create_chanmon_cfgs(2);
7606         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7607         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7608         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7609
7610         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7611         let logger = test_utils::TestLogger::new();
7612
7613
7614         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7615         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
7616         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();
7617         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7618
7619         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7620         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7621         assert_eq!(revoked_txn[0].output.len(), 4);
7622         assert_eq!(revoked_txn[0].input.len(), 1);
7623         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7624         let revoked_txid = revoked_txn[0].txid();
7625
7626         let mut penalty_sum = 0;
7627         for outp in revoked_txn[0].output.iter() {
7628                 if outp.script_pubkey.is_v0_p2wsh() {
7629                         penalty_sum += outp.value;
7630                 }
7631         }
7632
7633         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7634         let header_114 = connect_blocks(&nodes[1], 114, 0, false, Default::default());
7635
7636         // Actually revoke tx by claiming a HTLC
7637         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7638         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7639         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] }, 115);
7640         check_added_monitors!(nodes[1], 1);
7641
7642         // One or more justice tx should have been broadcast, check it
7643         let penalty_1;
7644         let feerate_1;
7645         {
7646                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7647                 assert_eq!(node_txn.len(), 3); // justice tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout (broadcasted from ChannelManager)
7648                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7649                 assert_eq!(node_txn[0].output.len(), 1);
7650                 check_spends!(node_txn[0], revoked_txn[0]);
7651                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7652                 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7653                 penalty_1 = node_txn[0].txid();
7654                 node_txn.clear();
7655         };
7656
7657         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7658         let header = connect_blocks(&nodes[1], 3, 115,  true, header.block_hash());
7659         let mut penalty_2 = penalty_1;
7660         let mut feerate_2 = 0;
7661         {
7662                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7663                 assert_eq!(node_txn.len(), 1);
7664                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7665                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7666                         assert_eq!(node_txn[0].output.len(), 1);
7667                         check_spends!(node_txn[0], revoked_txn[0]);
7668                         penalty_2 = node_txn[0].txid();
7669                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7670                         assert_ne!(penalty_2, penalty_1);
7671                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7672                         feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7673                         // Verify 25% bump heuristic
7674                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7675                         node_txn.clear();
7676                 }
7677         }
7678         assert_ne!(feerate_2, 0);
7679
7680         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7681         connect_blocks(&nodes[1], 3, 118, true, header);
7682         let penalty_3;
7683         let mut feerate_3 = 0;
7684         {
7685                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7686                 assert_eq!(node_txn.len(), 1);
7687                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7688                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7689                         assert_eq!(node_txn[0].output.len(), 1);
7690                         check_spends!(node_txn[0], revoked_txn[0]);
7691                         penalty_3 = node_txn[0].txid();
7692                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7693                         assert_ne!(penalty_3, penalty_2);
7694                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7695                         feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7696                         // Verify 25% bump heuristic
7697                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7698                         node_txn.clear();
7699                 }
7700         }
7701         assert_ne!(feerate_3, 0);
7702
7703         nodes[1].node.get_and_clear_pending_events();
7704         nodes[1].node.get_and_clear_pending_msg_events();
7705 }
7706
7707 #[test]
7708 fn test_bump_penalty_txn_on_revoked_htlcs() {
7709         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7710         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7711
7712         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7713         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7714         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7715         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7716         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7717
7718         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7719         // Lock HTLC in both directions
7720         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3_000_000).0;
7721         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7722
7723         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7724         assert_eq!(revoked_local_txn[0].input.len(), 1);
7725         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7726
7727         // Revoke local commitment tx
7728         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7729
7730         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7731         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7732         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
7733         check_closed_broadcast!(nodes[1], false);
7734         check_added_monitors!(nodes[1], 1);
7735
7736         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7737         assert_eq!(revoked_htlc_txn.len(), 4);
7738         if revoked_htlc_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7739                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7740                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7741                 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7742                 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7743                 assert_eq!(revoked_htlc_txn[1].output.len(), 1);
7744                 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7745         } else if revoked_htlc_txn[1].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7746                 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7747                 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7748                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7749                 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7750                 assert_eq!(revoked_htlc_txn[0].output.len(), 1);
7751                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7752         }
7753
7754         // Broadcast set of revoked txn on A
7755         let header_128 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7756         connect_block(&nodes[0], &Block { header: header_128, txdata: vec![revoked_local_txn[0].clone()] }, 128);
7757         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7758         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7759         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()] }, 129);
7760         let first;
7761         let feerate_1;
7762         let penalty_txn;
7763         {
7764                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7765                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7766                 // Verify claim tx are spending revoked HTLC txn
7767
7768                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7769                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7770                 // which are included in the same block (they are broadcasted because we scan the
7771                 // transactions linearly and generate claims as we go, they likely should be removed in the
7772                 // future).
7773                 assert_eq!(node_txn[0].input.len(), 1);
7774                 check_spends!(node_txn[0], revoked_local_txn[0]);
7775                 assert_eq!(node_txn[1].input.len(), 1);
7776                 check_spends!(node_txn[1], revoked_local_txn[0]);
7777                 assert_eq!(node_txn[2].input.len(), 1);
7778                 check_spends!(node_txn[2], revoked_local_txn[0]);
7779
7780                 // Each of the three justice transactions claim a separate (single) output of the three
7781                 // available, which we check here:
7782                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7783                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7784                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7785
7786                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7787                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7788
7789                 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7790                 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7791                 // a remote commitment tx has already been confirmed).
7792                 check_spends!(node_txn[3], chan.3);
7793
7794                 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7795                 // output, checked above).
7796                 assert_eq!(node_txn[4].input.len(), 2);
7797                 assert_eq!(node_txn[4].output.len(), 1);
7798                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7799
7800                 first = node_txn[4].txid();
7801                 // Store both feerates for later comparison
7802                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[4].output[0].value;
7803                 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7804                 penalty_txn = vec![node_txn[2].clone()];
7805                 node_txn.clear();
7806         }
7807
7808         // Connect one more block to see if bumped penalty are issued for HTLC txn
7809         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7810         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn }, 130);
7811         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7812         connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() }, 131);
7813         {
7814                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7815                 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7816
7817                 check_spends!(node_txn[0], revoked_local_txn[0]);
7818                 check_spends!(node_txn[1], revoked_local_txn[0]);
7819                 // Note that these are both bogus - they spend outputs already claimed in block 129:
7820                 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output  {
7821                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7822                 } else {
7823                         assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7824                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7825                 }
7826
7827                 node_txn.clear();
7828         };
7829
7830         // Few more blocks to confirm penalty txn
7831         let header_135 = connect_blocks(&nodes[0], 4, 131, true, header_131.block_hash());
7832         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7833         let header_144 = connect_blocks(&nodes[0], 9, 135, true, header_135);
7834         let node_txn = {
7835                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7836                 assert_eq!(node_txn.len(), 1);
7837
7838                 assert_eq!(node_txn[0].input.len(), 2);
7839                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7840                 // Verify bumped tx is different and 25% bump heuristic
7841                 assert_ne!(first, node_txn[0].txid());
7842                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7843                 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7844                 assert!(feerate_2 * 100 > feerate_1 * 125);
7845                 let txn = vec![node_txn[0].clone()];
7846                 node_txn.clear();
7847                 txn
7848         };
7849         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7850         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7851         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn }, 145);
7852         connect_blocks(&nodes[0], 20, 145, true, header_145.block_hash());
7853         {
7854                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7855                 // We verify than no new transaction has been broadcast because previously
7856                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7857                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7858                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7859                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7860                 // up bumped justice generation.
7861                 assert_eq!(node_txn.len(), 0);
7862                 node_txn.clear();
7863         }
7864         check_closed_broadcast!(nodes[0], false);
7865         check_added_monitors!(nodes[0], 1);
7866 }
7867
7868 #[test]
7869 fn test_bump_penalty_txn_on_remote_commitment() {
7870         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7871         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7872
7873         // Create 2 HTLCs
7874         // Provide preimage for one
7875         // Check aggregation
7876
7877         let chanmon_cfgs = create_chanmon_cfgs(2);
7878         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7879         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7880         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7881
7882         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7883         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7884         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7885
7886         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7887         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7888         assert_eq!(remote_txn[0].output.len(), 4);
7889         assert_eq!(remote_txn[0].input.len(), 1);
7890         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7891
7892         // Claim a HTLC without revocation (provide B monitor with preimage)
7893         nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000);
7894         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7895         connect_block(&nodes[1], &Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
7896         check_added_monitors!(nodes[1], 2);
7897
7898         // One or more claim tx should have been broadcast, check it
7899         let timeout;
7900         let preimage;
7901         let feerate_timeout;
7902         let feerate_preimage;
7903         {
7904                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7905                 assert_eq!(node_txn.len(), 5); // 2 * claim tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout + local HTLC-success (broadcasted from ChannelManager)
7906                 assert_eq!(node_txn[0].input.len(), 1);
7907                 assert_eq!(node_txn[1].input.len(), 1);
7908                 check_spends!(node_txn[0], remote_txn[0]);
7909                 check_spends!(node_txn[1], remote_txn[0]);
7910                 check_spends!(node_txn[2], chan.3);
7911                 check_spends!(node_txn[3], node_txn[2]);
7912                 check_spends!(node_txn[4], node_txn[2]);
7913                 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7914                         timeout = node_txn[0].txid();
7915                         let index = node_txn[0].input[0].previous_output.vout;
7916                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7917                         feerate_timeout = fee * 1000 / node_txn[0].get_weight() as u64;
7918
7919                         preimage = node_txn[1].txid();
7920                         let index = node_txn[1].input[0].previous_output.vout;
7921                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7922                         feerate_preimage = fee * 1000 / node_txn[1].get_weight() as u64;
7923                 } else {
7924                         timeout = node_txn[1].txid();
7925                         let index = node_txn[1].input[0].previous_output.vout;
7926                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7927                         feerate_timeout = fee * 1000 / node_txn[1].get_weight() as u64;
7928
7929                         preimage = node_txn[0].txid();
7930                         let index = node_txn[0].input[0].previous_output.vout;
7931                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7932                         feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7933                 }
7934                 node_txn.clear();
7935         };
7936         assert_ne!(feerate_timeout, 0);
7937         assert_ne!(feerate_preimage, 0);
7938
7939         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7940         connect_blocks(&nodes[1], 15, 1,  true, header.block_hash());
7941         {
7942                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7943                 assert_eq!(node_txn.len(), 2);
7944                 assert_eq!(node_txn[0].input.len(), 1);
7945                 assert_eq!(node_txn[1].input.len(), 1);
7946                 check_spends!(node_txn[0], remote_txn[0]);
7947                 check_spends!(node_txn[1], remote_txn[0]);
7948                 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7949                         let index = node_txn[0].input[0].previous_output.vout;
7950                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7951                         let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7952                         assert!(new_feerate * 100 > feerate_timeout * 125);
7953                         assert_ne!(timeout, node_txn[0].txid());
7954
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                         let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7958                         assert!(new_feerate * 100 > feerate_preimage * 125);
7959                         assert_ne!(preimage, node_txn[1].txid());
7960                 } else {
7961                         let index = node_txn[1].input[0].previous_output.vout;
7962                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7963                         let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7964                         assert!(new_feerate * 100 > feerate_timeout * 125);
7965                         assert_ne!(timeout, node_txn[1].txid());
7966
7967                         let index = node_txn[0].input[0].previous_output.vout;
7968                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7969                         let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7970                         assert!(new_feerate * 100 > feerate_preimage * 125);
7971                         assert_ne!(preimage, node_txn[0].txid());
7972                 }
7973                 node_txn.clear();
7974         }
7975
7976         nodes[1].node.get_and_clear_pending_events();
7977         nodes[1].node.get_and_clear_pending_msg_events();
7978 }
7979
7980 #[test]
7981 fn test_set_outpoints_partial_claiming() {
7982         // - remote party claim tx, new bump tx
7983         // - disconnect remote claiming tx, new bump
7984         // - disconnect tx, see no tx anymore
7985         let chanmon_cfgs = create_chanmon_cfgs(2);
7986         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7987         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7988         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7989
7990         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7991         let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7992         let payment_preimage_2 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7993
7994         // Remote commitment txn with 4 outputs: to_local, to_remote, 2 outgoing HTLC
7995         let remote_txn = get_local_commitment_txn!(nodes[1], chan.2);
7996         assert_eq!(remote_txn.len(), 3);
7997         assert_eq!(remote_txn[0].output.len(), 4);
7998         assert_eq!(remote_txn[0].input.len(), 1);
7999         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
8000         check_spends!(remote_txn[1], remote_txn[0]);
8001         check_spends!(remote_txn[2], remote_txn[0]);
8002
8003         // Connect blocks on node A to advance height towards TEST_FINAL_CLTV
8004         let prev_header_100 = connect_blocks(&nodes[1], 100, 0, false, Default::default());
8005         // Provide node A with both preimage
8006         nodes[0].node.claim_funds(payment_preimage_1, &None, 3_000_000);
8007         nodes[0].node.claim_funds(payment_preimage_2, &None, 3_000_000);
8008         check_added_monitors!(nodes[0], 2);
8009         nodes[0].node.get_and_clear_pending_events();
8010         nodes[0].node.get_and_clear_pending_msg_events();
8011
8012         // Connect blocks on node A commitment transaction
8013         let header = BlockHeader { version: 0x20000000, prev_blockhash: prev_header_100, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8014         connect_block(&nodes[0], &Block { header, txdata: vec![remote_txn[0].clone()] }, 101);
8015         check_closed_broadcast!(nodes[0], false);
8016         check_added_monitors!(nodes[0], 1);
8017         // Verify node A broadcast tx claiming both HTLCs
8018         {
8019                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8020                 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-Success*2
8021                 assert_eq!(node_txn.len(), 4);
8022                 check_spends!(node_txn[0], remote_txn[0]);
8023                 check_spends!(node_txn[1], chan.3);
8024                 check_spends!(node_txn[2], node_txn[1]);
8025                 check_spends!(node_txn[3], node_txn[1]);
8026                 assert_eq!(node_txn[0].input.len(), 2);
8027                 node_txn.clear();
8028         }
8029
8030         // Connect blocks on node B
8031         connect_blocks(&nodes[1], 135, 0, false, Default::default());
8032         check_closed_broadcast!(nodes[1], false);
8033         check_added_monitors!(nodes[1], 1);
8034         // Verify node B broadcast 2 HTLC-timeout txn
8035         let partial_claim_tx = {
8036                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8037                 assert_eq!(node_txn.len(), 3);
8038                 check_spends!(node_txn[1], node_txn[0]);
8039                 check_spends!(node_txn[2], node_txn[0]);
8040                 assert_eq!(node_txn[1].input.len(), 1);
8041                 assert_eq!(node_txn[2].input.len(), 1);
8042                 node_txn[1].clone()
8043         };
8044
8045         // Broadcast partial claim on node A, should regenerate a claiming tx with HTLC dropped
8046         let header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8047         connect_block(&nodes[0], &Block { header, txdata: vec![partial_claim_tx.clone()] }, 102);
8048         {
8049                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8050                 assert_eq!(node_txn.len(), 1);
8051                 check_spends!(node_txn[0], remote_txn[0]);
8052                 assert_eq!(node_txn[0].input.len(), 1); //dropped HTLC
8053                 node_txn.clear();
8054         }
8055         nodes[0].node.get_and_clear_pending_msg_events();
8056
8057         // Disconnect last block on node A, should regenerate a claiming tx with HTLC dropped
8058         disconnect_block(&nodes[0], &header, 102);
8059         {
8060                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8061                 assert_eq!(node_txn.len(), 1);
8062                 check_spends!(node_txn[0], remote_txn[0]);
8063                 assert_eq!(node_txn[0].input.len(), 2); //resurrected HTLC
8064                 node_txn.clear();
8065         }
8066
8067         //// Disconnect one more block and then reconnect multiple no transaction should be generated
8068         disconnect_block(&nodes[0], &header, 101);
8069         connect_blocks(&nodes[1], 15, 101, false, prev_header_100);
8070         {
8071                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8072                 assert_eq!(node_txn.len(), 0);
8073                 node_txn.clear();
8074         }
8075 }
8076
8077 #[test]
8078 fn test_counterparty_raa_skip_no_crash() {
8079         // Previously, if our counterparty sent two RAAs in a row without us having provided a
8080         // commitment transaction, we would have happily carried on and provided them the next
8081         // commitment transaction based on one RAA forward. This would probably eventually have led to
8082         // channel closure, but it would not have resulted in funds loss. Still, our
8083         // EnforcingChannelKeys would have paniced as it doesn't like jumps into the future. Here, we
8084         // check simply that the channel is closed in response to such an RAA, but don't check whether
8085         // we decide to punish our counterparty for revoking their funds (as we don't currently
8086         // implement that).
8087         let chanmon_cfgs = create_chanmon_cfgs(2);
8088         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8089         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8090         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8091         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8092
8093         let mut guard = nodes[0].node.channel_state.lock().unwrap();
8094         let keys = &guard.by_id.get_mut(&channel_id).unwrap().holder_keys;
8095         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8096         let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8097         // Must revoke without gaps
8098         keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8099         let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8100                 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8101
8102         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8103                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8104         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8105         check_added_monitors!(nodes[1], 1);
8106 }
8107
8108 #[test]
8109 fn test_bump_txn_sanitize_tracking_maps() {
8110         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8111         // verify we clean then right after expiration of ANTI_REORG_DELAY.
8112
8113         let chanmon_cfgs = create_chanmon_cfgs(2);
8114         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8115         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8116         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8117
8118         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8119         // Lock HTLC in both directions
8120         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8121         route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8122
8123         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8124         assert_eq!(revoked_local_txn[0].input.len(), 1);
8125         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8126
8127         // Revoke local commitment tx
8128         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 9_000_000);
8129
8130         // Broadcast set of revoked txn on A
8131         let header_128 = connect_blocks(&nodes[0], 128, 0,  false, Default::default());
8132         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8133
8134         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8135         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_local_txn[0].clone()] }, 129);
8136         check_closed_broadcast!(nodes[0], false);
8137         check_added_monitors!(nodes[0], 1);
8138         let penalty_txn = {
8139                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8140                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8141                 check_spends!(node_txn[0], revoked_local_txn[0]);
8142                 check_spends!(node_txn[1], revoked_local_txn[0]);
8143                 check_spends!(node_txn[2], revoked_local_txn[0]);
8144                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8145                 node_txn.clear();
8146                 penalty_txn
8147         };
8148         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8149         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn }, 130);
8150         connect_blocks(&nodes[0], 5, 130,  false, header_130.block_hash());
8151         {
8152                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap();
8153                 if let Some(monitor) = monitors.get(&OutPoint { txid: chan.3.txid(), index: 0 }) {
8154                         assert!(monitor.onchain_tx_handler.pending_claim_requests.is_empty());
8155                         assert!(monitor.onchain_tx_handler.claimable_outpoints.is_empty());
8156                 }
8157         }
8158 }
8159
8160 #[test]
8161 fn test_override_channel_config() {
8162         let chanmon_cfgs = create_chanmon_cfgs(2);
8163         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8164         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8165         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8166
8167         // Node0 initiates a channel to node1 using the override config.
8168         let mut override_config = UserConfig::default();
8169         override_config.own_channel_config.our_to_self_delay = 200;
8170
8171         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8172
8173         // Assert the channel created by node0 is using the override config.
8174         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8175         assert_eq!(res.channel_flags, 0);
8176         assert_eq!(res.to_self_delay, 200);
8177 }
8178
8179 #[test]
8180 fn test_override_0msat_htlc_minimum() {
8181         let mut zero_config = UserConfig::default();
8182         zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8183         let chanmon_cfgs = create_chanmon_cfgs(2);
8184         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8185         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8186         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8187
8188         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8189         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8190         assert_eq!(res.htlc_minimum_msat, 1);
8191
8192         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8193         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8194         assert_eq!(res.htlc_minimum_msat, 1);
8195 }
8196
8197 #[test]
8198 fn test_simple_payment_secret() {
8199         // Simple test of sending a payment with a payment_secret present. This does not use any AMP
8200         // features, however.
8201         let chanmon_cfgs = create_chanmon_cfgs(3);
8202         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8203         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8204         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8205
8206         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8207         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
8208         let logger = test_utils::TestLogger::new();
8209
8210         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8211         let payment_secret = PaymentSecret([0xdb; 32]);
8212         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8213         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();
8214         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2]]], 100000, payment_hash, Some(payment_secret.clone()));
8215         // Claiming with all the correct values but the wrong secret should result in nothing...
8216         assert_eq!(nodes[2].node.claim_funds(payment_preimage, &None, 100_000), false);
8217         assert_eq!(nodes[2].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 100_000), false);
8218         // ...but with the right secret we should be able to claim all the way back
8219         claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage, Some(payment_secret.clone()), 100_000);
8220 }
8221
8222 #[test]
8223 fn test_simple_mpp() {
8224         // Simple test of sending a multi-path payment.
8225         let chanmon_cfgs = create_chanmon_cfgs(4);
8226         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8227         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8228         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8229
8230         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8231         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8232         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8233         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8234         let logger = test_utils::TestLogger::new();
8235
8236         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8237         let payment_secret = PaymentSecret([0xdb; 32]);
8238         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8239         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();
8240         let path = route.paths[0].clone();
8241         route.paths.push(path);
8242         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8243         route.paths[0][0].short_channel_id = chan_1_id;
8244         route.paths[0][1].short_channel_id = chan_3_id;
8245         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8246         route.paths[1][0].short_channel_id = chan_2_id;
8247         route.paths[1][1].short_channel_id = chan_4_id;
8248         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, Some(payment_secret.clone()));
8249         // Claiming with all the correct values but the wrong secret should result in nothing...
8250         assert_eq!(nodes[3].node.claim_funds(payment_preimage, &None, 200_000), false);
8251         assert_eq!(nodes[3].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 200_000), false);
8252         // ...but with the right secret we should be able to claim all the way back
8253         claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage, Some(payment_secret), 200_000);
8254 }
8255
8256 #[test]
8257 fn test_update_err_monitor_lockdown() {
8258         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8259         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8260         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8261         //
8262         // This scenario may happen in a watchtower setup, where watchtower process a block height
8263         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8264         // commitment at same time.
8265
8266         let chanmon_cfgs = create_chanmon_cfgs(2);
8267         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8268         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8269         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8270
8271         // Create some initial channel
8272         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8273         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8274
8275         // Rebalance the network to generate htlc in the two directions
8276         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8277
8278         // Route a HTLC from node 0 to node 1 (but don't settle)
8279         let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8280
8281         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8282         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8283         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8284         let persister = test_utils::TestPersister::new();
8285         let watchtower = {
8286                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap();
8287                 let monitor = monitors.get(&outpoint).unwrap();
8288                 let mut w = test_utils::TestVecWriter(Vec::new());
8289                 monitor.write(&mut w).unwrap();
8290                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
8291                                 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8292                 assert!(new_monitor == *monitor);
8293                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8294                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8295                 watchtower
8296         };
8297         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8298         watchtower.chain_monitor.block_connected(&header, &[], 200);
8299
8300         // Try to update ChannelMonitor
8301         assert!(nodes[1].node.claim_funds(preimage, &None, 9_000_000));
8302         check_added_monitors!(nodes[1], 1);
8303         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8304         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8305         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8306         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8307                 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8308                         if let Err(_) =  watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8309                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8310                 } else { assert!(false); }
8311         } else { assert!(false); };
8312         // Our local monitor is in-sync and hasn't processed yet timeout
8313         check_added_monitors!(nodes[0], 1);
8314         let events = nodes[0].node.get_and_clear_pending_events();
8315         assert_eq!(events.len(), 1);
8316 }
8317
8318 #[test]
8319 fn test_concurrent_monitor_claim() {
8320         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8321         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8322         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8323         // state N+1 confirms. Alice claims output from state N+1.
8324
8325         let chanmon_cfgs = create_chanmon_cfgs(2);
8326         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8327         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8328         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8329
8330         // Create some initial channel
8331         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8332         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8333
8334         // Rebalance the network to generate htlc in the two directions
8335         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8336
8337         // Route a HTLC from node 0 to node 1 (but don't settle)
8338         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8339
8340         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8341         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8342         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8343         let persister = test_utils::TestPersister::new();
8344         let watchtower_alice = {
8345                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap();
8346                 let monitor = monitors.get(&outpoint).unwrap();
8347                 let mut w = test_utils::TestVecWriter(Vec::new());
8348                 monitor.write(&mut w).unwrap();
8349                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
8350                                 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8351                 assert!(new_monitor == *monitor);
8352                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8353                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8354                 watchtower
8355         };
8356         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8357         watchtower_alice.chain_monitor.block_connected(&header, &vec![], 135);
8358
8359         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8360         {
8361                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8362                 assert_eq!(txn.len(), 2);
8363                 txn.clear();
8364         }
8365
8366         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8367         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8368         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8369         let persister = test_utils::TestPersister::new();
8370         let watchtower_bob = {
8371                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap();
8372                 let monitor = monitors.get(&outpoint).unwrap();
8373                 let mut w = test_utils::TestVecWriter(Vec::new());
8374                 monitor.write(&mut w).unwrap();
8375                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
8376                                 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8377                 assert!(new_monitor == *monitor);
8378                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8379                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8380                 watchtower
8381         };
8382         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8383         watchtower_bob.chain_monitor.block_connected(&header, &vec![], 134);
8384
8385         // Route another payment to generate another update with still previous HTLC pending
8386         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
8387         {
8388                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
8389                 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();
8390                 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
8391         }
8392         check_added_monitors!(nodes[1], 1);
8393
8394         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8395         assert_eq!(updates.update_add_htlcs.len(), 1);
8396         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8397         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8398                 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8399                         // Watchtower Alice should already have seen the block and reject the update
8400                         if let Err(_) =  watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8401                         if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8402                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8403                 } else { assert!(false); }
8404         } else { assert!(false); };
8405         // Our local monitor is in-sync and hasn't processed yet timeout
8406         check_added_monitors!(nodes[0], 1);
8407
8408         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8409         watchtower_bob.chain_monitor.block_connected(&header, &vec![], 135);
8410
8411         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8412         let bob_state_y;
8413         {
8414                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8415                 assert_eq!(txn.len(), 2);
8416                 bob_state_y = txn[0].clone();
8417                 txn.clear();
8418         };
8419
8420         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8421         watchtower_alice.chain_monitor.block_connected(&header, &vec![(0, &bob_state_y)], 136);
8422         {
8423                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8424                 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8425                 // the onchain detection of the HTLC output
8426                 assert_eq!(htlc_txn.len(), 2);
8427                 check_spends!(htlc_txn[0], bob_state_y);
8428                 check_spends!(htlc_txn[1], bob_state_y);
8429         }
8430 }
8431
8432 #[test]
8433 fn test_pre_lockin_no_chan_closed_update() {
8434         // Test that if a peer closes a channel in response to a funding_created message we don't
8435         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8436         // message).
8437         //
8438         // Doing so would imply a channel monitor update before the initial channel monitor
8439         // registration, violating our API guarantees.
8440         //
8441         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8442         // then opening a second channel with the same funding output as the first (which is not
8443         // rejected because the first channel does not exist in the ChannelManager) and closing it
8444         // before receiving funding_signed.
8445         let chanmon_cfgs = create_chanmon_cfgs(2);
8446         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8447         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8448         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8449
8450         // Create an initial channel
8451         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8452         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8453         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8454         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8455         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8456
8457         // Move the first channel through the funding flow...
8458         let (temporary_channel_id, _tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8459
8460         nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
8461         check_added_monitors!(nodes[0], 0);
8462
8463         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8464         let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8465         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8466         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8467 }
8468
8469 #[test]
8470 fn test_htlc_no_detection() {
8471         // This test is a mutation to underscore the detection logic bug we had
8472         // before #653. HTLC value routed is above the remaining balance, thus
8473         // inverting HTLC and `to_remote` output. HTLC will come second and
8474         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8475         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8476         // outputs order detection for correct spending children filtring.
8477
8478         let chanmon_cfgs = create_chanmon_cfgs(2);
8479         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8480         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8481         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8482
8483         // Create some initial channels
8484         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8485
8486         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000, 1_000_000);
8487         let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8488         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8489         assert_eq!(local_txn[0].input.len(), 1);
8490         assert_eq!(local_txn[0].output.len(), 3);
8491         check_spends!(local_txn[0], chan_1.3);
8492
8493         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8494         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8495         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] }, 200);
8496         // We deliberately connect the local tx twice as this should provoke a failure calling
8497         // this test before #653 fix.
8498         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] }, 200);
8499         check_closed_broadcast!(nodes[0], false);
8500         check_added_monitors!(nodes[0], 1);
8501
8502         let htlc_timeout = {
8503                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8504                 assert_eq!(node_txn[0].input.len(), 1);
8505                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8506                 check_spends!(node_txn[0], local_txn[0]);
8507                 node_txn[0].clone()
8508         };
8509
8510         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8511         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
8512         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
8513         expect_payment_failed!(nodes[0], our_payment_hash, true);
8514 }
8515
8516 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8517         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8518         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8519         // Carol, Alice would be the upstream node, and Carol the downstream.)
8520         //
8521         // Steps of the test:
8522         // 1) Alice sends a HTLC to Carol through Bob.
8523         // 2) Carol doesn't settle the HTLC.
8524         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8525         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8526         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8527         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8528         // 5) Carol release the preimage to Bob off-chain.
8529         // 6) Bob claims the offered output on the broadcasted commitment.
8530         let chanmon_cfgs = create_chanmon_cfgs(3);
8531         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8532         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8533         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8534
8535         // Create some initial channels
8536         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8537         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8538
8539         // Steps (1) and (2):
8540         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8541         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3_000_000);
8542
8543         // Check that Alice's commitment transaction now contains an output for this HTLC.
8544         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8545         check_spends!(alice_txn[0], chan_ab.3);
8546         assert_eq!(alice_txn[0].output.len(), 2);
8547         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8548         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8549         assert_eq!(alice_txn.len(), 2);
8550
8551         // Steps (3) and (4):
8552         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8553         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8554         let mut force_closing_node = 0; // Alice force-closes
8555         if !broadcast_alice { force_closing_node = 1; } // Bob force-closes
8556         nodes[force_closing_node].node.force_close_channel(&chan_ab.2).unwrap();
8557         check_closed_broadcast!(nodes[force_closing_node], false);
8558         check_added_monitors!(nodes[force_closing_node], 1);
8559         if go_onchain_before_fulfill {
8560                 let txn_to_broadcast = match broadcast_alice {
8561                         true => alice_txn.clone(),
8562                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8563                 };
8564                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8565                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]}, 1);
8566                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8567                 if broadcast_alice {
8568                         check_closed_broadcast!(nodes[1], false);
8569                         check_added_monitors!(nodes[1], 1);
8570                 }
8571                 assert_eq!(bob_txn.len(), 1);
8572                 check_spends!(bob_txn[0], chan_ab.3);
8573         }
8574
8575         // Step (5):
8576         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8577         // process of removing the HTLC from their commitment transactions.
8578         assert!(nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000));
8579         check_added_monitors!(nodes[2], 1);
8580         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8581         assert!(carol_updates.update_add_htlcs.is_empty());
8582         assert!(carol_updates.update_fail_htlcs.is_empty());
8583         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8584         assert!(carol_updates.update_fee.is_none());
8585         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8586
8587         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8588         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8589         if !go_onchain_before_fulfill && broadcast_alice {
8590                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8591                 assert_eq!(events.len(), 1);
8592                 match events[0] {
8593                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8594                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8595                         },
8596                         _ => panic!("Unexpected event"),
8597                 };
8598         }
8599         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8600         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8601         // Carol<->Bob's updated commitment transaction info.
8602         check_added_monitors!(nodes[1], 2);
8603
8604         let events = nodes[1].node.get_and_clear_pending_msg_events();
8605         assert_eq!(events.len(), 2);
8606         let bob_revocation = match events[0] {
8607                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8608                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8609                         (*msg).clone()
8610                 },
8611                 _ => panic!("Unexpected event"),
8612         };
8613         let bob_updates = match events[1] {
8614                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8615                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8616                         (*updates).clone()
8617                 },
8618                 _ => panic!("Unexpected event"),
8619         };
8620
8621         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8622         check_added_monitors!(nodes[2], 1);
8623         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8624         check_added_monitors!(nodes[2], 1);
8625
8626         let events = nodes[2].node.get_and_clear_pending_msg_events();
8627         assert_eq!(events.len(), 1);
8628         let carol_revocation = match events[0] {
8629                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8630                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8631                         (*msg).clone()
8632                 },
8633                 _ => panic!("Unexpected event"),
8634         };
8635         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8636         check_added_monitors!(nodes[1], 1);
8637
8638         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8639         // here's where we put said channel's commitment tx on-chain.
8640         let mut txn_to_broadcast = alice_txn.clone();
8641         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8642         if !go_onchain_before_fulfill {
8643                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8644                 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]}, 1);
8645                 // If Bob was the one to force-close, he will have already passed these checks earlier.
8646                 if broadcast_alice {
8647                         check_closed_broadcast!(nodes[1], false);
8648                         check_added_monitors!(nodes[1], 1);
8649                 }
8650                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8651                 if broadcast_alice {
8652                         // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
8653                         // new block being connected. The ChannelManager being notified triggers a monitor update,
8654                         // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
8655                         // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
8656                         // broadcasted.
8657                         assert_eq!(bob_txn.len(), 3);
8658                         check_spends!(bob_txn[1], chan_ab.3);
8659                 } else {
8660                         assert_eq!(bob_txn.len(), 2);
8661                         check_spends!(bob_txn[0], chan_ab.3);
8662                 }
8663         }
8664
8665         // Step (6):
8666         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8667         // broadcasted commitment transaction.
8668         {
8669                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8670                 if go_onchain_before_fulfill {
8671                         // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
8672                         assert_eq!(bob_txn.len(), 2);
8673                 }
8674                 let script_weight = match broadcast_alice {
8675                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
8676                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8677                 };
8678                 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
8679                 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
8680                 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
8681                 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
8682                 if broadcast_alice && !go_onchain_before_fulfill {
8683                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8684                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8685                 } else {
8686                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
8687                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8688                 }
8689         }
8690 }
8691
8692 #[test]
8693 fn test_onchain_htlc_settlement_after_close() {
8694         do_test_onchain_htlc_settlement_after_close(true, true);
8695         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8696         do_test_onchain_htlc_settlement_after_close(true, false);
8697         do_test_onchain_htlc_settlement_after_close(false, false);
8698 }
8699
8700 #[test]
8701 fn test_duplicate_chan_id() {
8702         // Test that if a given peer tries to open a channel with the same channel_id as one that is
8703         // already open we reject it and keep the old channel.
8704         //
8705         // Previously, full_stack_target managed to figure out that if you tried to open two channels
8706         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8707         // the existing channel when we detect the duplicate new channel, screwing up our monitor
8708         // updating logic for the existing channel.
8709         let chanmon_cfgs = create_chanmon_cfgs(2);
8710         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8711         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8712         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8713
8714         // Create an initial channel
8715         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8716         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8717         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8718         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
8719
8720         // Try to create a second channel with the same temporary_channel_id as the first and check
8721         // that it is rejected.
8722         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8723         {
8724                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8725                 assert_eq!(events.len(), 1);
8726                 match events[0] {
8727                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8728                                 // Technically, at this point, nodes[1] would be justified in thinking both the
8729                                 // first (valid) and second (invalid) channels are closed, given they both have
8730                                 // the same non-temporary channel_id. However, currently we do not, so we just
8731                                 // move forward with it.
8732                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8733                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8734                         },
8735                         _ => panic!("Unexpected event"),
8736                 }
8737         }
8738
8739         // Move the first channel through the funding flow...
8740         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8741
8742         nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
8743         check_added_monitors!(nodes[0], 0);
8744
8745         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8746         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8747         {
8748                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8749                 assert_eq!(added_monitors.len(), 1);
8750                 assert_eq!(added_monitors[0].0, funding_output);
8751                 added_monitors.clear();
8752         }
8753         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8754
8755         let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8756         let channel_id = funding_outpoint.to_channel_id();
8757
8758         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8759         // temporary one).
8760
8761         // First try to open a second channel with a temporary channel id equal to the txid-based one.
8762         // Technically this is allowed by the spec, but we don't support it and there's little reason
8763         // to. Still, it shouldn't cause any other issues.
8764         open_chan_msg.temporary_channel_id = channel_id;
8765         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8766         {
8767                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8768                 assert_eq!(events.len(), 1);
8769                 match events[0] {
8770                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8771                                 // Technically, at this point, nodes[1] would be justified in thinking both
8772                                 // channels are closed, but currently we do not, so we just move forward with it.
8773                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8774                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8775                         },
8776                         _ => panic!("Unexpected event"),
8777                 }
8778         }
8779
8780         // Now try to create a second channel which has a duplicate funding output.
8781         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8782         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8783         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
8784         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
8785         create_funding_transaction(&nodes[0], 100000, 42); // Get and check the FundingGenerationReady event
8786
8787         let funding_created = {
8788                 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8789                 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
8790                 let logger = test_utils::TestLogger::new();
8791                 as_chan.get_outbound_funding_created(funding_outpoint, &&logger).unwrap()
8792         };
8793         check_added_monitors!(nodes[0], 0);
8794         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8795         // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
8796         // still needs to be cleared here.
8797         check_added_monitors!(nodes[1], 1);
8798
8799         // ...still, nodes[1] will reject the duplicate channel.
8800         {
8801                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8802                 assert_eq!(events.len(), 1);
8803                 match events[0] {
8804                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8805                                 // Technically, at this point, nodes[1] would be justified in thinking both
8806                                 // channels are closed, but currently we do not, so we just move forward with it.
8807                                 assert_eq!(msg.channel_id, channel_id);
8808                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8809                         },
8810                         _ => panic!("Unexpected event"),
8811                 }
8812         }
8813
8814         // finally, finish creating the original channel and send a payment over it to make sure
8815         // everything is functional.
8816         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8817         {
8818                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8819                 assert_eq!(added_monitors.len(), 1);
8820                 assert_eq!(added_monitors[0].0, funding_output);
8821                 added_monitors.clear();
8822         }
8823
8824         let events_4 = nodes[0].node.get_and_clear_pending_events();
8825         assert_eq!(events_4.len(), 1);
8826         match events_4[0] {
8827                 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
8828                         assert_eq!(user_channel_id, 42);
8829                         assert_eq!(*funding_txo, funding_output);
8830                 },
8831                 _ => panic!("Unexpected event"),
8832         };
8833
8834         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8835         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
8836         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8837         send_payment(&nodes[0], &[&nodes[1]], 8000000, 8_000_000);
8838 }