a94003c484aaa1dacab7b80b9232e32d78ab6331
[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::transaction::OutPoint;
15 use chain::keysinterface::{ChannelKeys, KeysInterface, SpendableOutputDescriptor};
16 use chain::chaininterface;
17 use chain::chaininterface::{ChainListener, ChainWatchInterfaceUtil, BlockNotifier};
18 use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
19 use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, RAACommitmentOrder, PaymentPreimage, PaymentHash, PaymentSecret, PaymentSendFailure, BREAKDOWN_TIMEOUT};
20 use ln::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ManyChannelMonitor, ANTI_REORG_DELAY};
21 use ln::channelmonitor;
22 use ln::channel::{Channel, ChannelError};
23 use ln::{chan_utils, onion_utils};
24 use routing::router::{Route, RouteHop, get_route};
25 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
26 use ln::msgs;
27 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler,HTLCFailChannelUpdate, ErrorAction};
28 use util::enforcing_trait_impls::EnforcingChannelKeys;
29 use util::{byte_utils, test_utils};
30 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
31 use util::errors::APIError;
32 use util::ser::{Writeable, ReadableArgs, Readable};
33 use util::config::UserConfig;
34
35 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
36 use bitcoin::hashes::HashEngine;
37 use bitcoin::hash_types::{Txid, BlockHash, WPubkeyHash};
38 use bitcoin::util::bip143;
39 use bitcoin::util::address::Address;
40 use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
41 use bitcoin::blockdata::block::{Block, BlockHeader};
42 use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType, OutPoint as BitcoinOutPoint};
43 use bitcoin::blockdata::script::{Builder, Script};
44 use bitcoin::blockdata::opcodes;
45 use bitcoin::blockdata::constants::genesis_block;
46 use bitcoin::network::constants::Network;
47
48 use bitcoin::hashes::sha256::Hash as Sha256;
49 use bitcoin::hashes::Hash;
50
51 use bitcoin::secp256k1::{Secp256k1, Message};
52 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
53
54 use regex;
55
56 use std::collections::{BTreeSet, HashMap, HashSet};
57 use std::default::Default;
58 use std::sync::{Arc, Mutex};
59 use std::sync::atomic::Ordering;
60 use std::mem;
61
62 use ln::functional_test_utils::*;
63 use ln::chan_utils::PreCalculatedTxCreationKeys;
64
65 #[test]
66 fn test_insane_channel_opens() {
67         // Stand up a network of 2 nodes
68         let chanmon_cfgs = create_chanmon_cfgs(2);
69         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
70         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
71         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
72
73         // Instantiate channel parameters where we push the maximum msats given our
74         // funding satoshis
75         let channel_value_sat = 31337; // same as funding satoshis
76         let channel_reserve_satoshis = Channel::<EnforcingChannelKeys>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
77         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
78
79         // Have node0 initiate a channel to node1 with aforementioned parameters
80         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
81
82         // Extract the channel open message from node0 to node1
83         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
84
85         // Test helper that asserts we get the correct error string given a mutator
86         // that supposedly makes the channel open message insane
87         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
88                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
89                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
90                 assert_eq!(msg_events.len(), 1);
91                 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
92                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
93                         match action {
94                                 &ErrorAction::SendErrorMessage { .. } => {
95                                         nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
96                                 },
97                                 _ => panic!("unexpected event!"),
98                         }
99                 } else { assert!(false); }
100         };
101
102         use ln::channel::MAX_FUNDING_SATOSHIS;
103         use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
104
105         // Test all mutations that would make the channel open message insane
106         insane_open_helper(format!("Funding must be smaller than {}. It was {}", MAX_FUNDING_SATOSHIS, MAX_FUNDING_SATOSHIS).as_str(), |mut msg| { msg.funding_satoshis = MAX_FUNDING_SATOSHIS; msg });
107
108         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
109
110         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 });
111
112         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
113
114         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 });
115
116         insane_open_helper(r"Minimum htlc value \(\d+\) was larger than full channel value \(\d+\)", |mut msg| { msg.htlc_minimum_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000; msg });
117
118         insane_open_helper("They wanted our payments to be delayed by a needlessly long period", |mut msg| { msg.to_self_delay = MAX_LOCAL_BREAKDOWN_TIMEOUT + 1; msg });
119
120         insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
121
122         insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
123 }
124
125 #[test]
126 fn test_async_inbound_update_fee() {
127         let chanmon_cfgs = create_chanmon_cfgs(2);
128         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
129         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
130         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
131         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
132         let logger = test_utils::TestLogger::new();
133         let channel_id = chan.2;
134
135         // balancing
136         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
137
138         // A                                        B
139         // update_fee                            ->
140         // send (1) commitment_signed            -.
141         //                                       <- update_add_htlc/commitment_signed
142         // send (2) RAA (awaiting remote revoke) -.
143         // (1) commitment_signed is delivered    ->
144         //                                       .- send (3) RAA (awaiting remote revoke)
145         // (2) RAA is delivered                  ->
146         //                                       .- send (4) commitment_signed
147         //                                       <- (3) RAA is delivered
148         // send (5) commitment_signed            -.
149         //                                       <- (4) commitment_signed is delivered
150         // send (6) RAA                          -.
151         // (5) commitment_signed is delivered    ->
152         //                                       <- RAA
153         // (6) RAA is delivered                  ->
154
155         // First nodes[0] generates an update_fee
156         nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
157         check_added_monitors!(nodes[0], 1);
158
159         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
160         assert_eq!(events_0.len(), 1);
161         let (update_msg, commitment_signed) = match events_0[0] { // (1)
162                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
163                         (update_fee.as_ref(), commitment_signed)
164                 },
165                 _ => panic!("Unexpected event"),
166         };
167
168         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
169
170         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
171         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
172         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
173         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();
174         check_added_monitors!(nodes[1], 1);
175
176         let payment_event = {
177                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
178                 assert_eq!(events_1.len(), 1);
179                 SendEvent::from_event(events_1.remove(0))
180         };
181         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
182         assert_eq!(payment_event.msgs.len(), 1);
183
184         // ...now when the messages get delivered everyone should be happy
185         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
186         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
187         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
188         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
189         check_added_monitors!(nodes[0], 1);
190
191         // deliver(1), generate (3):
192         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
193         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
194         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
195         check_added_monitors!(nodes[1], 1);
196
197         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
198         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
199         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
200         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
201         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
202         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
203         assert!(bs_update.update_fee.is_none()); // (4)
204         check_added_monitors!(nodes[1], 1);
205
206         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
207         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
208         assert!(as_update.update_add_htlcs.is_empty()); // (5)
209         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
210         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
211         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
212         assert!(as_update.update_fee.is_none()); // (5)
213         check_added_monitors!(nodes[0], 1);
214
215         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
216         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
217         // only (6) so get_event_msg's assert(len == 1) passes
218         check_added_monitors!(nodes[0], 1);
219
220         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
221         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
222         check_added_monitors!(nodes[1], 1);
223
224         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
225         check_added_monitors!(nodes[0], 1);
226
227         let events_2 = nodes[0].node.get_and_clear_pending_events();
228         assert_eq!(events_2.len(), 1);
229         match events_2[0] {
230                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
231                 _ => panic!("Unexpected event"),
232         }
233
234         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
235         check_added_monitors!(nodes[1], 1);
236 }
237
238 #[test]
239 fn test_update_fee_unordered_raa() {
240         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
241         // crash in an earlier version of the update_fee patch)
242         let chanmon_cfgs = create_chanmon_cfgs(2);
243         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
244         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
245         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
246         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
247         let channel_id = chan.2;
248         let logger = test_utils::TestLogger::new();
249
250         // balancing
251         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
252
253         // First nodes[0] generates an update_fee
254         nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
255         check_added_monitors!(nodes[0], 1);
256
257         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
258         assert_eq!(events_0.len(), 1);
259         let update_msg = match events_0[0] { // (1)
260                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
261                         update_fee.as_ref()
262                 },
263                 _ => panic!("Unexpected event"),
264         };
265
266         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
267
268         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
269         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
270         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
271         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();
272         check_added_monitors!(nodes[1], 1);
273
274         let payment_event = {
275                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
276                 assert_eq!(events_1.len(), 1);
277                 SendEvent::from_event(events_1.remove(0))
278         };
279         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
280         assert_eq!(payment_event.msgs.len(), 1);
281
282         // ...now when the messages get delivered everyone should be happy
283         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
284         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
285         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
286         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
287         check_added_monitors!(nodes[0], 1);
288
289         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
290         check_added_monitors!(nodes[1], 1);
291
292         // We can't continue, sadly, because our (1) now has a bogus signature
293 }
294
295 #[test]
296 fn test_multi_flight_update_fee() {
297         let chanmon_cfgs = create_chanmon_cfgs(2);
298         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
299         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
300         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
301         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
302         let channel_id = chan.2;
303
304         // A                                        B
305         // update_fee/commitment_signed          ->
306         //                                       .- send (1) RAA and (2) commitment_signed
307         // update_fee (never committed)          ->
308         // (3) update_fee                        ->
309         // We have to manually generate the above update_fee, it is allowed by the protocol but we
310         // don't track which updates correspond to which revoke_and_ack responses so we're in
311         // AwaitingRAA mode and will not generate the update_fee yet.
312         //                                       <- (1) RAA delivered
313         // (3) is generated and send (4) CS      -.
314         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
315         // know the per_commitment_point to use for it.
316         //                                       <- (2) commitment_signed delivered
317         // revoke_and_ack                        ->
318         //                                          B should send no response here
319         // (4) commitment_signed delivered       ->
320         //                                       <- RAA/commitment_signed delivered
321         // revoke_and_ack                        ->
322
323         // First nodes[0] generates an update_fee
324         let initial_feerate = get_feerate!(nodes[0], channel_id);
325         nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
326         check_added_monitors!(nodes[0], 1);
327
328         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
329         assert_eq!(events_0.len(), 1);
330         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
331                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
332                         (update_fee.as_ref().unwrap(), commitment_signed)
333                 },
334                 _ => panic!("Unexpected event"),
335         };
336
337         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
338         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
339         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
340         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
341         check_added_monitors!(nodes[1], 1);
342
343         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
344         // transaction:
345         nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
346         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
347         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
348
349         // Create the (3) update_fee message that nodes[0] will generate before it does...
350         let mut update_msg_2 = msgs::UpdateFee {
351                 channel_id: update_msg_1.channel_id.clone(),
352                 feerate_per_kw: (initial_feerate + 30) as u32,
353         };
354
355         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
356
357         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
358         // Deliver (3)
359         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
360
361         // Deliver (1), generating (3) and (4)
362         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
363         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
364         check_added_monitors!(nodes[0], 1);
365         assert!(as_second_update.update_add_htlcs.is_empty());
366         assert!(as_second_update.update_fulfill_htlcs.is_empty());
367         assert!(as_second_update.update_fail_htlcs.is_empty());
368         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
369         // Check that the update_fee newly generated matches what we delivered:
370         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
371         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
372
373         // Deliver (2) commitment_signed
374         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
375         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
376         check_added_monitors!(nodes[0], 1);
377         // No commitment_signed so get_event_msg's assert(len == 1) passes
378
379         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
380         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
381         check_added_monitors!(nodes[1], 1);
382
383         // Delever (4)
384         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
385         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
386         check_added_monitors!(nodes[1], 1);
387
388         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
389         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
390         check_added_monitors!(nodes[0], 1);
391
392         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
393         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
394         // No commitment_signed so get_event_msg's assert(len == 1) passes
395         check_added_monitors!(nodes[0], 1);
396
397         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
398         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
399         check_added_monitors!(nodes[1], 1);
400 }
401
402 #[test]
403 fn test_1_conf_open() {
404         // Previously, if the minium_depth config was set to 1, we'd never send a funding_locked. This
405         // tests that we properly send one in that case.
406         let mut alice_config = UserConfig::default();
407         alice_config.own_channel_config.minimum_depth = 1;
408         alice_config.channel_options.announced_channel = true;
409         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
410         let mut bob_config = UserConfig::default();
411         bob_config.own_channel_config.minimum_depth = 1;
412         bob_config.channel_options.announced_channel = true;
413         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
414         let chanmon_cfgs = create_chanmon_cfgs(2);
415         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
416         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(alice_config), Some(bob_config)]);
417         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
418
419         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
420         assert!(nodes[0].chain_monitor.does_match_tx(&tx));
421         assert!(nodes[1].chain_monitor.does_match_tx(&tx));
422
423         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
424         nodes[1].block_notifier.block_connected_checked(&header, 1, &[&tx; 1], &[tx.version as usize; 1]);
425         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()));
426
427         nodes[0].block_notifier.block_connected_checked(&header, 1, &[&tx; 1], &[tx.version as usize; 1]);
428         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
429         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
430
431         for node in nodes {
432                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
433                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
434                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
435         }
436 }
437
438 fn do_test_sanity_on_in_flight_opens(steps: u8) {
439         // Previously, we had issues deserializing channels when we hadn't connected the first block
440         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
441         // serialization round-trips and simply do steps towards opening a channel and then drop the
442         // Node objects.
443
444         let chanmon_cfgs = create_chanmon_cfgs(2);
445         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
446         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
447         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
448
449         if steps & 0b1000_0000 != 0{
450                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
451                 nodes[0].block_notifier.block_connected_checked(&header, 1, &Vec::new(), &[0; 0]);
452                 nodes[1].block_notifier.block_connected_checked(&header, 1, &Vec::new(), &[0; 0]);
453         }
454
455         if steps & 0x0f == 0 { return; }
456         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
457         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
458
459         if steps & 0x0f == 1 { return; }
460         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
461         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
462
463         if steps & 0x0f == 2 { return; }
464         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
465
466         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
467
468         if steps & 0x0f == 3 { return; }
469         nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
470         check_added_monitors!(nodes[0], 0);
471         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
472
473         if steps & 0x0f == 4 { return; }
474         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
475         {
476                 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
477                 assert_eq!(added_monitors.len(), 1);
478                 assert_eq!(added_monitors[0].0, funding_output);
479                 added_monitors.clear();
480         }
481         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
482
483         if steps & 0x0f == 5 { return; }
484         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
485         {
486                 let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
487                 assert_eq!(added_monitors.len(), 1);
488                 assert_eq!(added_monitors[0].0, funding_output);
489                 added_monitors.clear();
490         }
491
492         let events_4 = nodes[0].node.get_and_clear_pending_events();
493         assert_eq!(events_4.len(), 1);
494         match events_4[0] {
495                 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
496                         assert_eq!(user_channel_id, 42);
497                         assert_eq!(*funding_txo, funding_output);
498                 },
499                 _ => panic!("Unexpected event"),
500         };
501
502         if steps & 0x0f == 6 { return; }
503         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx);
504
505         if steps & 0x0f == 7 { return; }
506         confirm_transaction(&nodes[0].block_notifier, &nodes[0].chain_monitor, &tx, tx.version);
507         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
508 }
509
510 #[test]
511 fn test_sanity_on_in_flight_opens() {
512         do_test_sanity_on_in_flight_opens(0);
513         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
514         do_test_sanity_on_in_flight_opens(1);
515         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
516         do_test_sanity_on_in_flight_opens(2);
517         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
518         do_test_sanity_on_in_flight_opens(3);
519         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
520         do_test_sanity_on_in_flight_opens(4);
521         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
522         do_test_sanity_on_in_flight_opens(5);
523         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
524         do_test_sanity_on_in_flight_opens(6);
525         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
526         do_test_sanity_on_in_flight_opens(7);
527         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
528         do_test_sanity_on_in_flight_opens(8);
529         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
530 }
531
532 #[test]
533 fn test_update_fee_vanilla() {
534         let chanmon_cfgs = create_chanmon_cfgs(2);
535         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
536         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
537         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
538         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
539         let channel_id = chan.2;
540
541         let feerate = get_feerate!(nodes[0], channel_id);
542         nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
543         check_added_monitors!(nodes[0], 1);
544
545         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
546         assert_eq!(events_0.len(), 1);
547         let (update_msg, commitment_signed) = match events_0[0] {
548                         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 } } => {
549                         (update_fee.as_ref(), commitment_signed)
550                 },
551                 _ => panic!("Unexpected event"),
552         };
553         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
554
555         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
556         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
557         check_added_monitors!(nodes[1], 1);
558
559         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
560         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
561         check_added_monitors!(nodes[0], 1);
562
563         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
564         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
565         // No commitment_signed so get_event_msg's assert(len == 1) passes
566         check_added_monitors!(nodes[0], 1);
567
568         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
569         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
570         check_added_monitors!(nodes[1], 1);
571 }
572
573 #[test]
574 fn test_update_fee_that_funder_cannot_afford() {
575         let chanmon_cfgs = create_chanmon_cfgs(2);
576         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
577         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
578         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
579         let channel_value = 1888;
580         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000, InitFeatures::known(), InitFeatures::known());
581         let channel_id = chan.2;
582
583         let feerate = 260;
584         nodes[0].node.update_fee(channel_id, feerate).unwrap();
585         check_added_monitors!(nodes[0], 1);
586         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
587
588         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
589
590         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
591
592         //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
593         //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
594         {
595                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
596
597                 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
598                 let num_htlcs = commitment_tx.output.len() - 2;
599                 let total_fee: u64 = feerate as u64 * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
600                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
601                 actual_fee = channel_value - actual_fee;
602                 assert_eq!(total_fee, actual_fee);
603         }
604
605         //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
606         //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
607         nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
608         check_added_monitors!(nodes[0], 1);
609
610         let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
611
612         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap());
613
614         //While producing the commitment_signed response after handling a received update_fee request the
615         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
616         //Should produce and error.
617         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed);
618         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
619         check_added_monitors!(nodes[1], 1);
620         check_closed_broadcast!(nodes[1], true);
621 }
622
623 #[test]
624 fn test_update_fee_with_fundee_update_add_htlc() {
625         let chanmon_cfgs = create_chanmon_cfgs(2);
626         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
627         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
628         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
629         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
630         let channel_id = chan.2;
631         let logger = test_utils::TestLogger::new();
632
633         // balancing
634         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
635
636         let feerate = get_feerate!(nodes[0], channel_id);
637         nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
638         check_added_monitors!(nodes[0], 1);
639
640         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
641         assert_eq!(events_0.len(), 1);
642         let (update_msg, commitment_signed) = match events_0[0] {
643                         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 } } => {
644                         (update_fee.as_ref(), commitment_signed)
645                 },
646                 _ => panic!("Unexpected event"),
647         };
648         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
649         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
650         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
651         check_added_monitors!(nodes[1], 1);
652
653         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
654         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
655         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();
656
657         // nothing happens since node[1] is in AwaitingRemoteRevoke
658         nodes[1].node.send_payment(&route, our_payment_hash, &None).unwrap();
659         {
660                 let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
661                 assert_eq!(added_monitors.len(), 0);
662                 added_monitors.clear();
663         }
664         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
665         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
666         // node[1] has nothing to do
667
668         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
669         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
670         check_added_monitors!(nodes[0], 1);
671
672         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
673         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
674         // No commitment_signed so get_event_msg's assert(len == 1) passes
675         check_added_monitors!(nodes[0], 1);
676         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
677         check_added_monitors!(nodes[1], 1);
678         // AwaitingRemoteRevoke ends here
679
680         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
681         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
682         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
683         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
684         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
685         assert_eq!(commitment_update.update_fee.is_none(), true);
686
687         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
688         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
689         check_added_monitors!(nodes[0], 1);
690         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
691
692         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
693         check_added_monitors!(nodes[1], 1);
694         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
695
696         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
697         check_added_monitors!(nodes[1], 1);
698         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
699         // No commitment_signed so get_event_msg's assert(len == 1) passes
700
701         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
702         check_added_monitors!(nodes[0], 1);
703         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
704
705         expect_pending_htlcs_forwardable!(nodes[0]);
706
707         let events = nodes[0].node.get_and_clear_pending_events();
708         assert_eq!(events.len(), 1);
709         match events[0] {
710                 Event::PaymentReceived { .. } => { },
711                 _ => panic!("Unexpected event"),
712         };
713
714         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage, 800_000);
715
716         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000, 800_000);
717         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000, 800_000);
718         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
719 }
720
721 #[test]
722 fn test_update_fee() {
723         let chanmon_cfgs = create_chanmon_cfgs(2);
724         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
725         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
726         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
727         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
728         let channel_id = chan.2;
729
730         // A                                        B
731         // (1) update_fee/commitment_signed      ->
732         //                                       <- (2) revoke_and_ack
733         //                                       .- send (3) commitment_signed
734         // (4) update_fee/commitment_signed      ->
735         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
736         //                                       <- (3) commitment_signed delivered
737         // send (6) revoke_and_ack               -.
738         //                                       <- (5) deliver revoke_and_ack
739         // (6) deliver revoke_and_ack            ->
740         //                                       .- send (7) commitment_signed in response to (4)
741         //                                       <- (7) deliver commitment_signed
742         // revoke_and_ack                        ->
743
744         // Create and deliver (1)...
745         let feerate = get_feerate!(nodes[0], channel_id);
746         nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
747         check_added_monitors!(nodes[0], 1);
748
749         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
750         assert_eq!(events_0.len(), 1);
751         let (update_msg, commitment_signed) = match events_0[0] {
752                         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 } } => {
753                         (update_fee.as_ref(), commitment_signed)
754                 },
755                 _ => panic!("Unexpected event"),
756         };
757         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
758
759         // Generate (2) and (3):
760         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
761         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
762         check_added_monitors!(nodes[1], 1);
763
764         // Deliver (2):
765         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
766         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
767         check_added_monitors!(nodes[0], 1);
768
769         // Create and deliver (4)...
770         nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
771         check_added_monitors!(nodes[0], 1);
772         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
773         assert_eq!(events_0.len(), 1);
774         let (update_msg, commitment_signed) = match events_0[0] {
775                         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 } } => {
776                         (update_fee.as_ref(), commitment_signed)
777                 },
778                 _ => panic!("Unexpected event"),
779         };
780
781         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
782         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
783         check_added_monitors!(nodes[1], 1);
784         // ... creating (5)
785         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
786         // No commitment_signed so get_event_msg's assert(len == 1) passes
787
788         // Handle (3), creating (6):
789         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
790         check_added_monitors!(nodes[0], 1);
791         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
792         // No commitment_signed so get_event_msg's assert(len == 1) passes
793
794         // Deliver (5):
795         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
796         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
797         check_added_monitors!(nodes[0], 1);
798
799         // Deliver (6), creating (7):
800         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
801         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
802         assert!(commitment_update.update_add_htlcs.is_empty());
803         assert!(commitment_update.update_fulfill_htlcs.is_empty());
804         assert!(commitment_update.update_fail_htlcs.is_empty());
805         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
806         assert!(commitment_update.update_fee.is_none());
807         check_added_monitors!(nodes[1], 1);
808
809         // Deliver (7)
810         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
811         check_added_monitors!(nodes[0], 1);
812         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
813         // No commitment_signed so get_event_msg's assert(len == 1) passes
814
815         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
816         check_added_monitors!(nodes[1], 1);
817         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
818
819         assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
820         assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
821         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
822 }
823
824 #[test]
825 fn pre_funding_lock_shutdown_test() {
826         // Test sending a shutdown prior to funding_locked after funding generation
827         let chanmon_cfgs = create_chanmon_cfgs(2);
828         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
829         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
830         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
831         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0, InitFeatures::known(), InitFeatures::known());
832         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
833         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![tx.clone()]}, 1);
834         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![tx.clone()]}, 1);
835
836         nodes[0].node.close_channel(&OutPoint { txid: tx.txid(), index: 0 }.to_channel_id()).unwrap();
837         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
838         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
839         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
840         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
841
842         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
843         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
844         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
845         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
846         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
847         assert!(node_0_none.is_none());
848
849         assert!(nodes[0].node.list_channels().is_empty());
850         assert!(nodes[1].node.list_channels().is_empty());
851 }
852
853 #[test]
854 fn updates_shutdown_wait() {
855         // Test sending a shutdown with outstanding updates pending
856         let chanmon_cfgs = create_chanmon_cfgs(3);
857         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
858         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
859         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
860         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
861         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
862         let logger = test_utils::TestLogger::new();
863
864         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
865
866         nodes[0].node.close_channel(&chan_1.2).unwrap();
867         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
868         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
869         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
870         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
871
872         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
873         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
874
875         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
876
877         let net_graph_msg_handler0 = &nodes[0].net_graph_msg_handler;
878         let net_graph_msg_handler1 = &nodes[1].net_graph_msg_handler;
879         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();
880         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();
881         unwrap_send_err!(nodes[0].node.send_payment(&route_1, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
882         unwrap_send_err!(nodes[1].node.send_payment(&route_2, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
883
884         assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
885         check_added_monitors!(nodes[2], 1);
886         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
887         assert!(updates.update_add_htlcs.is_empty());
888         assert!(updates.update_fail_htlcs.is_empty());
889         assert!(updates.update_fail_malformed_htlcs.is_empty());
890         assert!(updates.update_fee.is_none());
891         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
892         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
893         check_added_monitors!(nodes[1], 1);
894         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
895         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
896
897         assert!(updates_2.update_add_htlcs.is_empty());
898         assert!(updates_2.update_fail_htlcs.is_empty());
899         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
900         assert!(updates_2.update_fee.is_none());
901         assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
902         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
903         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
904
905         let events = nodes[0].node.get_and_clear_pending_events();
906         assert_eq!(events.len(), 1);
907         match events[0] {
908                 Event::PaymentSent { ref payment_preimage } => {
909                         assert_eq!(our_payment_preimage, *payment_preimage);
910                 },
911                 _ => panic!("Unexpected event"),
912         }
913
914         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
915         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
916         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
917         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
918         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
919         assert!(node_0_none.is_none());
920
921         assert!(nodes[0].node.list_channels().is_empty());
922
923         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
924         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
925         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
926         assert!(nodes[1].node.list_channels().is_empty());
927         assert!(nodes[2].node.list_channels().is_empty());
928 }
929
930 #[test]
931 fn htlc_fail_async_shutdown() {
932         // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
933         let chanmon_cfgs = create_chanmon_cfgs(3);
934         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
935         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
936         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
937         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
938         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
939         let logger = test_utils::TestLogger::new();
940
941         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
942         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
943         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();
944         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
945         check_added_monitors!(nodes[0], 1);
946         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
947         assert_eq!(updates.update_add_htlcs.len(), 1);
948         assert!(updates.update_fulfill_htlcs.is_empty());
949         assert!(updates.update_fail_htlcs.is_empty());
950         assert!(updates.update_fail_malformed_htlcs.is_empty());
951         assert!(updates.update_fee.is_none());
952
953         nodes[1].node.close_channel(&chan_1.2).unwrap();
954         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
955         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
956         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
957
958         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
959         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
960         check_added_monitors!(nodes[1], 1);
961         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
962         commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
963
964         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
965         assert!(updates_2.update_add_htlcs.is_empty());
966         assert!(updates_2.update_fulfill_htlcs.is_empty());
967         assert_eq!(updates_2.update_fail_htlcs.len(), 1);
968         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
969         assert!(updates_2.update_fee.is_none());
970
971         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]);
972         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
973
974         expect_payment_failed!(nodes[0], our_payment_hash, false);
975
976         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
977         assert_eq!(msg_events.len(), 2);
978         let node_0_closing_signed = match msg_events[0] {
979                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
980                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
981                         (*msg).clone()
982                 },
983                 _ => panic!("Unexpected event"),
984         };
985         match msg_events[1] {
986                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
987                         assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
988                 },
989                 _ => panic!("Unexpected event"),
990         }
991
992         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
993         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
994         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
995         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
996         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
997         assert!(node_0_none.is_none());
998
999         assert!(nodes[0].node.list_channels().is_empty());
1000
1001         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1002         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1003         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1004         assert!(nodes[1].node.list_channels().is_empty());
1005         assert!(nodes[2].node.list_channels().is_empty());
1006 }
1007
1008 fn do_test_shutdown_rebroadcast(recv_count: u8) {
1009         // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
1010         // messages delivered prior to disconnect
1011         let chanmon_cfgs = create_chanmon_cfgs(3);
1012         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1013         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1014         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1015         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1016         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1017
1018         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
1019
1020         nodes[1].node.close_channel(&chan_1.2).unwrap();
1021         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1022         if recv_count > 0 {
1023                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
1024                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1025                 if recv_count > 1 {
1026                         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
1027                 }
1028         }
1029
1030         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1031         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1032
1033         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1034         let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1035         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1036         let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1037
1038         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish);
1039         let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1040         assert!(node_1_shutdown == node_1_2nd_shutdown);
1041
1042         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish);
1043         let node_0_2nd_shutdown = if recv_count > 0 {
1044                 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1045                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
1046                 node_0_2nd_shutdown
1047         } else {
1048                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1049                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
1050                 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
1051         };
1052         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown);
1053
1054         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1055         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1056
1057         assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
1058         check_added_monitors!(nodes[2], 1);
1059         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1060         assert!(updates.update_add_htlcs.is_empty());
1061         assert!(updates.update_fail_htlcs.is_empty());
1062         assert!(updates.update_fail_malformed_htlcs.is_empty());
1063         assert!(updates.update_fee.is_none());
1064         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
1065         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
1066         check_added_monitors!(nodes[1], 1);
1067         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1068         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
1069
1070         assert!(updates_2.update_add_htlcs.is_empty());
1071         assert!(updates_2.update_fail_htlcs.is_empty());
1072         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
1073         assert!(updates_2.update_fee.is_none());
1074         assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
1075         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
1076         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
1077
1078         let events = nodes[0].node.get_and_clear_pending_events();
1079         assert_eq!(events.len(), 1);
1080         match events[0] {
1081                 Event::PaymentSent { ref payment_preimage } => {
1082                         assert_eq!(our_payment_preimage, *payment_preimage);
1083                 },
1084                 _ => panic!("Unexpected event"),
1085         }
1086
1087         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1088         if recv_count > 0 {
1089                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
1090                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1091                 assert!(node_1_closing_signed.is_some());
1092         }
1093
1094         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1095         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1096
1097         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1098         let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1099         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1100         if recv_count == 0 {
1101                 // If all closing_signeds weren't delivered we can just resume where we left off...
1102                 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1103
1104                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish);
1105                 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1106                 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
1107
1108                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1109                 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1110                 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
1111
1112                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown);
1113                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1114
1115                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown);
1116                 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1117                 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
1118
1119                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed);
1120                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1121                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
1122                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1123                 assert!(node_0_none.is_none());
1124         } else {
1125                 // If one node, however, received + responded with an identical closing_signed we end
1126                 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
1127                 // There isn't really anything better we can do simply, but in the future we might
1128                 // explore storing a set of recently-closed channels that got disconnected during
1129                 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
1130                 // give our counterparty enough time to (potentially) broadcast a cooperative closing
1131                 // transaction.
1132                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1133
1134                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1135                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1136                 assert_eq!(msg_events.len(), 1);
1137                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
1138                         match action {
1139                                 &ErrorAction::SendErrorMessage { ref msg } => {
1140                                         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
1141                                         assert_eq!(msg.channel_id, chan_1.2);
1142                                 },
1143                                 _ => panic!("Unexpected event!"),
1144                         }
1145                 } else { panic!("Needed SendErrorMessage close"); }
1146
1147                 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
1148                 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
1149                 // closing_signed so we do it ourselves
1150                 check_closed_broadcast!(nodes[0], false);
1151                 check_added_monitors!(nodes[0], 1);
1152         }
1153
1154         assert!(nodes[0].node.list_channels().is_empty());
1155
1156         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1157         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1158         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1159         assert!(nodes[1].node.list_channels().is_empty());
1160         assert!(nodes[2].node.list_channels().is_empty());
1161 }
1162
1163 #[test]
1164 fn test_shutdown_rebroadcast() {
1165         do_test_shutdown_rebroadcast(0);
1166         do_test_shutdown_rebroadcast(1);
1167         do_test_shutdown_rebroadcast(2);
1168 }
1169
1170 #[test]
1171 fn fake_network_test() {
1172         // Simple test which builds a network of ChannelManagers, connects them to each other, and
1173         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
1174         let chanmon_cfgs = create_chanmon_cfgs(4);
1175         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1176         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1177         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1178
1179         // Create some initial channels
1180         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1181         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1182         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1183
1184         // Rebalance the network a bit by relaying one payment through all the channels...
1185         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
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
1190         // Send some more payments
1191         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000, 1_000_000);
1192         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000, 1_000_000);
1193         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000, 1_000_000);
1194
1195         // Test failure packets
1196         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1197         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1198
1199         // Add a new channel that skips 3
1200         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1201
1202         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000, 1_000_000);
1203         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000, 1_000_000);
1204         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_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
1210         // Do some rebalance loop payments, simultaneously
1211         let mut hops = Vec::with_capacity(3);
1212         hops.push(RouteHop {
1213                 pubkey: nodes[2].node.get_our_node_id(),
1214                 node_features: NodeFeatures::empty(),
1215                 short_channel_id: chan_2.0.contents.short_channel_id,
1216                 channel_features: ChannelFeatures::empty(),
1217                 fee_msat: 0,
1218                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1219         });
1220         hops.push(RouteHop {
1221                 pubkey: nodes[3].node.get_our_node_id(),
1222                 node_features: NodeFeatures::empty(),
1223                 short_channel_id: chan_3.0.contents.short_channel_id,
1224                 channel_features: ChannelFeatures::empty(),
1225                 fee_msat: 0,
1226                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1227         });
1228         hops.push(RouteHop {
1229                 pubkey: nodes[1].node.get_our_node_id(),
1230                 node_features: NodeFeatures::empty(),
1231                 short_channel_id: chan_4.0.contents.short_channel_id,
1232                 channel_features: ChannelFeatures::empty(),
1233                 fee_msat: 1000000,
1234                 cltv_expiry_delta: TEST_FINAL_CLTV,
1235         });
1236         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;
1237         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;
1238         let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1239
1240         let mut hops = Vec::with_capacity(3);
1241         hops.push(RouteHop {
1242                 pubkey: nodes[3].node.get_our_node_id(),
1243                 node_features: NodeFeatures::empty(),
1244                 short_channel_id: chan_4.0.contents.short_channel_id,
1245                 channel_features: ChannelFeatures::empty(),
1246                 fee_msat: 0,
1247                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1248         });
1249         hops.push(RouteHop {
1250                 pubkey: nodes[2].node.get_our_node_id(),
1251                 node_features: NodeFeatures::empty(),
1252                 short_channel_id: chan_3.0.contents.short_channel_id,
1253                 channel_features: ChannelFeatures::empty(),
1254                 fee_msat: 0,
1255                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1256         });
1257         hops.push(RouteHop {
1258                 pubkey: nodes[1].node.get_our_node_id(),
1259                 node_features: NodeFeatures::empty(),
1260                 short_channel_id: chan_2.0.contents.short_channel_id,
1261                 channel_features: ChannelFeatures::empty(),
1262                 fee_msat: 1000000,
1263                 cltv_expiry_delta: TEST_FINAL_CLTV,
1264         });
1265         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;
1266         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;
1267         let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1268
1269         // Claim the rebalances...
1270         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1271         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1, 1_000_000);
1272
1273         // Add a duplicate new channel from 2 to 4
1274         let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1275
1276         // Send some payments across both channels
1277         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1278         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1279         let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1280
1281
1282         route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1283         let events = nodes[0].node.get_and_clear_pending_msg_events();
1284         assert_eq!(events.len(), 0);
1285         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);
1286
1287         //TODO: Test that routes work again here as we've been notified that the channel is full
1288
1289         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3, 3_000_000);
1290         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4, 3_000_000);
1291         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5, 3_000_000);
1292
1293         // Close down the channels...
1294         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1295         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1296         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1297         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1298         close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1299 }
1300
1301 #[test]
1302 fn holding_cell_htlc_counting() {
1303         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1304         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1305         // commitment dance rounds.
1306         let chanmon_cfgs = create_chanmon_cfgs(3);
1307         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1308         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1309         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1310         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1311         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1312         let logger = test_utils::TestLogger::new();
1313
1314         let mut payments = Vec::new();
1315         for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1316                 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1317                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1318                 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();
1319                 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
1320                 payments.push((payment_preimage, payment_hash));
1321         }
1322         check_added_monitors!(nodes[1], 1);
1323
1324         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1325         assert_eq!(events.len(), 1);
1326         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1327         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1328
1329         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1330         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1331         // another HTLC.
1332         let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
1333         {
1334                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1335                 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();
1336                 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &None), true, APIError::ChannelUnavailable { ref err },
1337                         assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1338                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1339                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1340         }
1341
1342         // This should also be true if we try to forward a payment.
1343         let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
1344         {
1345                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1346                 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();
1347                 nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
1348                 check_added_monitors!(nodes[0], 1);
1349         }
1350
1351         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1352         assert_eq!(events.len(), 1);
1353         let payment_event = SendEvent::from_event(events.pop().unwrap());
1354         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1355
1356         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1357         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1358         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1359         // fails), the second will process the resulting failure and fail the HTLC backward.
1360         expect_pending_htlcs_forwardable!(nodes[1]);
1361         expect_pending_htlcs_forwardable!(nodes[1]);
1362         check_added_monitors!(nodes[1], 1);
1363
1364         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1365         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1366         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1367
1368         let events = nodes[0].node.get_and_clear_pending_msg_events();
1369         assert_eq!(events.len(), 1);
1370         match events[0] {
1371                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
1372                         assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
1373                 },
1374                 _ => panic!("Unexpected event"),
1375         }
1376
1377         expect_payment_failed!(nodes[0], payment_hash_2, false);
1378
1379         // Now forward all the pending HTLCs and claim them back
1380         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1381         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1382         check_added_monitors!(nodes[2], 1);
1383
1384         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1385         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1386         check_added_monitors!(nodes[1], 1);
1387         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1388
1389         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1390         check_added_monitors!(nodes[1], 1);
1391         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1392
1393         for ref update in as_updates.update_add_htlcs.iter() {
1394                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1395         }
1396         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1397         check_added_monitors!(nodes[2], 1);
1398         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1399         check_added_monitors!(nodes[2], 1);
1400         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1401
1402         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1403         check_added_monitors!(nodes[1], 1);
1404         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1405         check_added_monitors!(nodes[1], 1);
1406         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1407
1408         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1409         check_added_monitors!(nodes[2], 1);
1410
1411         expect_pending_htlcs_forwardable!(nodes[2]);
1412
1413         let events = nodes[2].node.get_and_clear_pending_events();
1414         assert_eq!(events.len(), payments.len());
1415         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1416                 match event {
1417                         &Event::PaymentReceived { ref payment_hash, .. } => {
1418                                 assert_eq!(*payment_hash, *hash);
1419                         },
1420                         _ => panic!("Unexpected event"),
1421                 };
1422         }
1423
1424         for (preimage, _) in payments.drain(..) {
1425                 claim_payment(&nodes[1], &[&nodes[2]], preimage, 100_000);
1426         }
1427
1428         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000, 1_000_000);
1429 }
1430
1431 #[test]
1432 fn duplicate_htlc_test() {
1433         // Test that we accept duplicate payment_hash HTLCs across the network and that
1434         // claiming/failing them are all separate and don't affect each other
1435         let chanmon_cfgs = create_chanmon_cfgs(6);
1436         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1437         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1438         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1439
1440         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1441         create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1442         create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1443         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1444         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1445         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1446
1447         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1448
1449         *nodes[0].network_payment_count.borrow_mut() -= 1;
1450         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1451
1452         *nodes[0].network_payment_count.borrow_mut() -= 1;
1453         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1454
1455         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage, 1_000_000);
1456         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1457         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage, 1_000_000);
1458 }
1459
1460 #[test]
1461 fn test_duplicate_htlc_different_direction_onchain() {
1462         // Test that ChannelMonitor doesn't generate 2 preimage txn
1463         // when we have 2 HTLCs with same preimage that go across a node
1464         // in opposite directions.
1465         let chanmon_cfgs = create_chanmon_cfgs(2);
1466         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1467         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1468         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1469
1470         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1471         let logger = test_utils::TestLogger::new();
1472
1473         // balancing
1474         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
1475
1476         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1477
1478         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1479         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();
1480         send_along_route_with_hash(&nodes[1], route, &vec!(&nodes[0])[..], 800_000, payment_hash);
1481
1482         // Provide preimage to node 0 by claiming payment
1483         nodes[0].node.claim_funds(payment_preimage, &None, 800_000);
1484         check_added_monitors!(nodes[0], 1);
1485
1486         // Broadcast node 1 commitment txn
1487         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1488
1489         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1490         let mut has_both_htlcs = 0; // check htlcs match ones committed
1491         for outp in remote_txn[0].output.iter() {
1492                 if outp.value == 800_000 / 1000 {
1493                         has_both_htlcs += 1;
1494                 } else if outp.value == 900_000 / 1000 {
1495                         has_both_htlcs += 1;
1496                 }
1497         }
1498         assert_eq!(has_both_htlcs, 2);
1499
1500         let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1501         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
1502         check_added_monitors!(nodes[0], 1);
1503
1504         // Check we only broadcast 1 timeout tx
1505         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1506         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()) };
1507         assert_eq!(claim_txn.len(), 5);
1508         check_spends!(claim_txn[2], chan_1.3);
1509         check_spends!(claim_txn[3], claim_txn[2]);
1510         assert_eq!(htlc_pair.0.input.len(), 1);
1511         assert_eq!(htlc_pair.0.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1512         check_spends!(htlc_pair.0, remote_txn[0]);
1513         assert_eq!(htlc_pair.1.input.len(), 1);
1514         assert_eq!(htlc_pair.1.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1515         check_spends!(htlc_pair.1, remote_txn[0]);
1516
1517         let events = nodes[0].node.get_and_clear_pending_msg_events();
1518         assert_eq!(events.len(), 2);
1519         for e in events {
1520                 match e {
1521                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1522                         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, .. } } => {
1523                                 assert!(update_add_htlcs.is_empty());
1524                                 assert!(update_fail_htlcs.is_empty());
1525                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1526                                 assert!(update_fail_malformed_htlcs.is_empty());
1527                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1528                         },
1529                         _ => panic!("Unexpected event"),
1530                 }
1531         }
1532 }
1533
1534 #[test]
1535 fn test_basic_channel_reserve() {
1536         let chanmon_cfgs = create_chanmon_cfgs(2);
1537         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1538         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1539         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1540         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1541         let logger = test_utils::TestLogger::new();
1542
1543         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1544         let channel_reserve = chan_stat.channel_reserve_msat;
1545
1546         // The 2* and +1 are for the fee spike reserve.
1547         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
1548         let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1);
1549         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1550         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1551         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();
1552         let err = nodes[0].node.send_payment(&route, our_payment_hash, &None).err().unwrap();
1553         match err {
1554                 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1555                         match &fails[0] {
1556                                 &APIError::ChannelUnavailable{ref err} =>
1557                                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1558                                 _ => panic!("Unexpected error variant"),
1559                         }
1560                 },
1561                 _ => panic!("Unexpected error variant"),
1562         }
1563         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1564         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);
1565
1566         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send, max_can_send);
1567 }
1568
1569 #[test]
1570 fn test_fee_spike_violation_fails_htlc() {
1571         let chanmon_cfgs = create_chanmon_cfgs(2);
1572         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1573         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1574         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1575         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1576         let logger = test_utils::TestLogger::new();
1577
1578         macro_rules! get_route_and_payment_hash {
1579                 ($recv_value: expr) => {{
1580                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1581                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler.network_graph.read().unwrap();
1582                         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();
1583                         (route, payment_hash, payment_preimage)
1584                 }}
1585         };
1586
1587         let (route, payment_hash, _) = get_route_and_payment_hash!(3460001);
1588         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1589         let secp_ctx = Secp256k1::new();
1590         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1591
1592         let cur_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1593
1594         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1595         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &None, cur_height).unwrap();
1596         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1597         let msg = msgs::UpdateAddHTLC {
1598                 channel_id: chan.2,
1599                 htlc_id: 0,
1600                 amount_msat: htlc_msat,
1601                 payment_hash: payment_hash,
1602                 cltv_expiry: htlc_cltv,
1603                 onion_routing_packet: onion_packet,
1604         };
1605
1606         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1607
1608         // Now manually create the commitment_signed message corresponding to the update_add
1609         // nodes[0] just sent. In the code for construction of this message, "local" refers
1610         // to the sender of the message, and "remote" refers to the receiver.
1611
1612         let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1613
1614         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1615
1616         // Get the EnforcingChannelKeys for each channel, which will be used to (1) get the keys
1617         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1618         let (local_revocation_basepoint, local_htlc_basepoint, local_payment_point, local_secret, local_secret2) = {
1619                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1620                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1621                 let chan_keys = local_chan.get_keys();
1622                 let pubkeys = chan_keys.pubkeys();
1623                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint, pubkeys.payment_point,
1624                  chan_keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER), chan_keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2))
1625         };
1626         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_payment_point, remote_secret1) = {
1627                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1628                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1629                 let chan_keys = remote_chan.get_keys();
1630                 let pubkeys = chan_keys.pubkeys();
1631                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint, pubkeys.payment_point,
1632                  chan_keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1))
1633         };
1634
1635         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1636         let commitment_secret = SecretKey::from_slice(&remote_secret1).unwrap();
1637         let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &commitment_secret);
1638         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &per_commitment_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         let static_payment_pk = local_payment_point.serialize();
1645         let remote_commit_tx_output = TxOut {
1646                                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0)
1647                                                              .push_slice(&WPubkeyHash::hash(&static_payment_pk)[..])
1648                                                              .into_script(),
1649                 value: local_chan_balance as u64
1650         };
1651
1652         let local_commit_tx_output = TxOut {
1653                 script_pubkey: chan_utils::get_revokeable_redeemscript(&commit_tx_keys.revocation_key,
1654                                                                                BREAKDOWN_TIMEOUT,
1655                                                                                &commit_tx_keys.broadcaster_delayed_payment_key).to_v0_p2wsh(),
1656                                 value: 95000,
1657         };
1658
1659         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1660                 offered: false,
1661                 amount_msat: 3460001,
1662                 cltv_expiry: htlc_cltv,
1663                 payment_hash: payment_hash,
1664                 transaction_output_index: Some(1),
1665         };
1666
1667         let htlc_output = TxOut {
1668                 script_pubkey: chan_utils::get_htlc_redeemscript(&accepted_htlc_info, &commit_tx_keys).to_v0_p2wsh(),
1669                 value: 3460001 / 1000
1670         };
1671
1672         let commit_tx_obscure_factor = {
1673                 let mut sha = Sha256::engine();
1674                 let remote_payment_point = &remote_payment_point.serialize();
1675                 sha.input(&local_payment_point.serialize());
1676                 sha.input(remote_payment_point);
1677                 let res = Sha256::from_engine(sha).into_inner();
1678
1679                 ((res[26] as u64) << 5*8) |
1680                 ((res[27] as u64) << 4*8) |
1681                 ((res[28] as u64) << 3*8) |
1682                 ((res[29] as u64) << 2*8) |
1683                 ((res[30] as u64) << 1*8) |
1684                 ((res[31] as u64) << 0*8)
1685         };
1686         let commitment_number = 1;
1687         let obscured_commitment_transaction_number = commit_tx_obscure_factor ^ commitment_number;
1688         let lock_time = ((0x20 as u32) << 8*3) | ((obscured_commitment_transaction_number & 0xffffffu64) as u32);
1689         let input = TxIn {
1690                 previous_output: BitcoinOutPoint { txid: chan.3.txid(), vout: 0 },
1691                 script_sig: Script::new(),
1692                 sequence: ((0x80 as u32) << 8*3) | ((obscured_commitment_transaction_number >> 3*8) as u32),
1693                 witness: Vec::new(),
1694         };
1695
1696         let commit_tx = Transaction {
1697                 version: 2,
1698                 lock_time,
1699                 input: vec![input],
1700                 output: vec![remote_commit_tx_output, htlc_output, local_commit_tx_output],
1701         };
1702         let res = {
1703                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1704                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1705                 let local_chan_keys = local_chan.get_keys();
1706                 let pre_commit_tx_keys = PreCalculatedTxCreationKeys::new(commit_tx_keys);
1707                 local_chan_keys.sign_counterparty_commitment(feerate_per_kw, &commit_tx, &pre_commit_tx_keys, &[&accepted_htlc_info], &secp_ctx).unwrap()
1708         };
1709
1710         let commit_signed_msg = msgs::CommitmentSigned {
1711                 channel_id: chan.2,
1712                 signature: res.0,
1713                 htlc_signatures: res.1
1714         };
1715
1716         // Send the commitment_signed message to the nodes[1].
1717         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1718         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1719
1720         // Send the RAA to nodes[1].
1721         let per_commitment_secret = local_secret;
1722         let next_secret = SecretKey::from_slice(&local_secret2).unwrap();
1723         let next_per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &next_secret);
1724         let raa_msg = msgs::RevokeAndACK{ channel_id: chan.2, per_commitment_secret, next_per_commitment_point};
1725         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1726
1727         let events = nodes[1].node.get_and_clear_pending_msg_events();
1728         assert_eq!(events.len(), 1);
1729         // Make sure the HTLC failed in the way we expect.
1730         match events[0] {
1731                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1732                         assert_eq!(update_fail_htlcs.len(), 1);
1733                         update_fail_htlcs[0].clone()
1734                 },
1735                 _ => panic!("Unexpected event"),
1736         };
1737         nodes[1].logger.assert_log("lightning::ln::channel".to_string(), "Attempting to fail HTLC due to fee spike buffer violation".to_string(), 1);
1738
1739         check_added_monitors!(nodes[1], 2);
1740 }
1741
1742 #[test]
1743 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1744         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1745         // Set the fee rate for the channel very high, to the point where the fundee
1746         // sending any amount would result in a channel reserve violation. In this test
1747         // we check that we would be prevented from sending an HTLC in this situation.
1748         chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1749         chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1750         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1751         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1752         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1753         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1754         let logger = test_utils::TestLogger::new();
1755
1756         macro_rules! get_route_and_payment_hash {
1757                 ($recv_value: expr) => {{
1758                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1759                         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1760                         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();
1761                         (route, payment_hash, payment_preimage)
1762                 }}
1763         };
1764
1765         let (route, our_payment_hash, _) = get_route_and_payment_hash!(1000);
1766         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1767                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1768         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1769         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);
1770 }
1771
1772 #[test]
1773 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1774         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1775         // Set the fee rate for the channel very high, to the point where the funder
1776         // receiving 1 update_add_htlc would result in them closing the channel due
1777         // to channel reserve violation. This close could also happen if the fee went
1778         // up a more realistic amount, but many HTLCs were outstanding at the time of
1779         // the update_add_htlc.
1780         chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1781         chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1782         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1783         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1784         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1785         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1786         let logger = test_utils::TestLogger::new();
1787
1788         macro_rules! get_route_and_payment_hash {
1789                 ($recv_value: expr) => {{
1790                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1791                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1792                         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();
1793                         (route, payment_hash, payment_preimage)
1794                 }}
1795         };
1796
1797         let (route, payment_hash, _) = get_route_and_payment_hash!(1000);
1798         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1799         let secp_ctx = Secp256k1::new();
1800         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1801         let cur_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1802         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1803         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 1000, &None, cur_height).unwrap();
1804         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1805         let msg = msgs::UpdateAddHTLC {
1806                 channel_id: chan.2,
1807                 htlc_id: 1,
1808                 amount_msat: htlc_msat + 1,
1809                 payment_hash: payment_hash,
1810                 cltv_expiry: htlc_cltv,
1811                 onion_routing_packet: onion_packet,
1812         };
1813
1814         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1815         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1816         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);
1817         assert_eq!(nodes[0].node.list_channels().len(), 0);
1818         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1819         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1820         check_added_monitors!(nodes[0], 1);
1821 }
1822
1823 #[test]
1824 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1825         let chanmon_cfgs = create_chanmon_cfgs(3);
1826         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1827         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1828         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1829         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1830         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1831         let logger = test_utils::TestLogger::new();
1832
1833         macro_rules! get_route_and_payment_hash {
1834                 ($recv_value: expr) => {{
1835                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1836                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1837                         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();
1838                         (route, payment_hash, payment_preimage)
1839                 }}
1840         };
1841
1842         let feemsat = 239;
1843         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1844         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1845         let feerate = get_feerate!(nodes[0], chan.2);
1846
1847         // Add a 2* and +1 for the fee spike reserve.
1848         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1);
1849         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;
1850         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1851
1852         // Add a pending HTLC.
1853         let (route_1, our_payment_hash_1, _) = get_route_and_payment_hash!(amt_msat_1);
1854         let payment_event_1 = {
1855                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
1856                 check_added_monitors!(nodes[0], 1);
1857
1858                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1859                 assert_eq!(events.len(), 1);
1860                 SendEvent::from_event(events.remove(0))
1861         };
1862         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1863
1864         // Attempt to trigger a channel reserve violation --> payment failure.
1865         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2);
1866         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;
1867         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1868         let (route_2, _, _) = get_route_and_payment_hash!(amt_msat_2);
1869
1870         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1871         let secp_ctx = Secp256k1::new();
1872         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1873         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1874         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1875         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height).unwrap();
1876         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1877         let msg = msgs::UpdateAddHTLC {
1878                 channel_id: chan.2,
1879                 htlc_id: 1,
1880                 amount_msat: htlc_msat + 1,
1881                 payment_hash: our_payment_hash_1,
1882                 cltv_expiry: htlc_cltv,
1883                 onion_routing_packet: onion_packet,
1884         };
1885
1886         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1887         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1888         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1889         assert_eq!(nodes[1].node.list_channels().len(), 1);
1890         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1891         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1892         check_added_monitors!(nodes[1], 1);
1893 }
1894
1895 #[test]
1896 fn test_inbound_outbound_capacity_is_not_zero() {
1897         let chanmon_cfgs = create_chanmon_cfgs(2);
1898         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1899         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1900         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1901         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1902         let channels0 = node_chanmgrs[0].list_channels();
1903         let channels1 = node_chanmgrs[1].list_channels();
1904         assert_eq!(channels0.len(), 1);
1905         assert_eq!(channels1.len(), 1);
1906
1907         assert_eq!(channels0[0].inbound_capacity_msat, 95000000);
1908         assert_eq!(channels1[0].outbound_capacity_msat, 95000000);
1909
1910         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000);
1911         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000);
1912 }
1913
1914 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64) -> u64 {
1915         (COMMITMENT_TX_BASE_WEIGHT + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1916 }
1917
1918 #[test]
1919 fn test_channel_reserve_holding_cell_htlcs() {
1920         let chanmon_cfgs = create_chanmon_cfgs(3);
1921         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1922         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1923         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1924         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1925         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1926         let logger = test_utils::TestLogger::new();
1927
1928         let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1929         let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1930
1931         let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1932         let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1933
1934         macro_rules! get_route_and_payment_hash {
1935                 ($recv_value: expr) => {{
1936                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1937                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1938                         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();
1939                         (route, payment_hash, payment_preimage)
1940                 }}
1941         };
1942
1943         macro_rules! expect_forward {
1944                 ($node: expr) => {{
1945                         let mut events = $node.node.get_and_clear_pending_msg_events();
1946                         assert_eq!(events.len(), 1);
1947                         check_added_monitors!($node, 1);
1948                         let payment_event = SendEvent::from_event(events.remove(0));
1949                         payment_event
1950                 }}
1951         }
1952
1953         let feemsat = 239; // somehow we know?
1954         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1955         let feerate = get_feerate!(nodes[0], chan_1.2);
1956
1957         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1958
1959         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1960         {
1961                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
1962                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1963                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1964                         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)));
1965                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1966                 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);
1967         }
1968
1969         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1970         // nodes[0]'s wealth
1971         loop {
1972                 let amt_msat = recv_value_0 + total_fee_msat;
1973                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1974                 // Also, ensure that each payment has enough to be over the dust limit to
1975                 // ensure it'll be included in each commit tx fee calculation.
1976                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1977                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1978                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1979                         break;
1980                 }
1981                 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0, recv_value_0);
1982
1983                 let (stat01_, stat11_, stat12_, stat22_) = (
1984                         get_channel_value_stat!(nodes[0], chan_1.2),
1985                         get_channel_value_stat!(nodes[1], chan_1.2),
1986                         get_channel_value_stat!(nodes[1], chan_2.2),
1987                         get_channel_value_stat!(nodes[2], chan_2.2),
1988                 );
1989
1990                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1991                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1992                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1993                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1994                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1995         }
1996
1997         // adding pending output.
1998         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1999         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
2000         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
2001         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
2002         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
2003         // cases where 1 msat over X amount will cause a payment failure, but anything less than
2004         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
2005         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
2006         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
2007         // policy.
2008         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1);
2009         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
2010         let amt_msat_1 = recv_value_1 + total_fee_msat;
2011
2012         let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
2013         let payment_event_1 = {
2014                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
2015                 check_added_monitors!(nodes[0], 1);
2016
2017                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2018                 assert_eq!(events.len(), 1);
2019                 SendEvent::from_event(events.remove(0))
2020         };
2021         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
2022
2023         // channel reserve test with htlc pending output > 0
2024         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
2025         {
2026                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
2027                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
2028                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
2029                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2030         }
2031
2032         // split the rest to test holding cell
2033         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
2034         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
2035         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
2036         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
2037         {
2038                 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
2039                 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);
2040         }
2041
2042         // now see if they go through on both sides
2043         let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
2044         // but this will stuck in the holding cell
2045         nodes[0].node.send_payment(&route_21, our_payment_hash_21, &None).unwrap();
2046         check_added_monitors!(nodes[0], 0);
2047         let events = nodes[0].node.get_and_clear_pending_events();
2048         assert_eq!(events.len(), 0);
2049
2050         // test with outbound holding cell amount > 0
2051         {
2052                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
2053                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
2054                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
2055                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2056                 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);
2057         }
2058
2059         let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
2060         // this will also stuck in the holding cell
2061         nodes[0].node.send_payment(&route_22, our_payment_hash_22, &None).unwrap();
2062         check_added_monitors!(nodes[0], 0);
2063         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
2064         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2065
2066         // flush the pending htlc
2067         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
2068         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2069         check_added_monitors!(nodes[1], 1);
2070
2071         // the pending htlc should be promoted to committed
2072         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
2073         check_added_monitors!(nodes[0], 1);
2074         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2075
2076         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
2077         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2078         // No commitment_signed so get_event_msg's assert(len == 1) passes
2079         check_added_monitors!(nodes[0], 1);
2080
2081         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
2082         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2083         check_added_monitors!(nodes[1], 1);
2084
2085         expect_pending_htlcs_forwardable!(nodes[1]);
2086
2087         let ref payment_event_11 = expect_forward!(nodes[1]);
2088         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
2089         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
2090
2091         expect_pending_htlcs_forwardable!(nodes[2]);
2092         expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
2093
2094         // flush the htlcs in the holding cell
2095         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
2096         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
2097         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
2098         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
2099         expect_pending_htlcs_forwardable!(nodes[1]);
2100
2101         let ref payment_event_3 = expect_forward!(nodes[1]);
2102         assert_eq!(payment_event_3.msgs.len(), 2);
2103         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
2104         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
2105
2106         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2107         expect_pending_htlcs_forwardable!(nodes[2]);
2108
2109         let events = nodes[2].node.get_and_clear_pending_events();
2110         assert_eq!(events.len(), 2);
2111         match events[0] {
2112                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2113                         assert_eq!(our_payment_hash_21, *payment_hash);
2114                         assert_eq!(*payment_secret, None);
2115                         assert_eq!(recv_value_21, amt);
2116                 },
2117                 _ => panic!("Unexpected event"),
2118         }
2119         match events[1] {
2120                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2121                         assert_eq!(our_payment_hash_22, *payment_hash);
2122                         assert_eq!(None, *payment_secret);
2123                         assert_eq!(recv_value_22, amt);
2124                 },
2125                 _ => panic!("Unexpected event"),
2126         }
2127
2128         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1, recv_value_1);
2129         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21, recv_value_21);
2130         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22, recv_value_22);
2131
2132         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1);
2133         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2134         {
2135                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_3 + 1);
2136                 let err = nodes[0].node.send_payment(&route, our_payment_hash, &None).err().unwrap();
2137                 match err {
2138                         PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
2139                                 match &fails[0] {
2140                                         &APIError::ChannelUnavailable{ref err} =>
2141                                                 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
2142                                         _ => panic!("Unexpected error variant"),
2143                                 }
2144                         },
2145                         _ => panic!("Unexpected error variant"),
2146                 }
2147                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2148                 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);
2149         }
2150
2151         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3, recv_value_3);
2152
2153         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1);
2154         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);
2155         let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2156         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2157         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2158
2159         let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2160         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2161 }
2162
2163 #[test]
2164 fn channel_reserve_in_flight_removes() {
2165         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2166         // can send to its counterparty, but due to update ordering, the other side may not yet have
2167         // considered those HTLCs fully removed.
2168         // This tests that we don't count HTLCs which will not be included in the next remote
2169         // commitment transaction towards the reserve value (as it implies no commitment transaction
2170         // will be generated which violates the remote reserve value).
2171         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2172         // To test this we:
2173         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2174         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2175         //    you only consider the value of the first HTLC, it may not),
2176         //  * start routing a third HTLC from A to B,
2177         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2178         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2179         //  * deliver the first fulfill from B
2180         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2181         //    claim,
2182         //  * deliver A's response CS and RAA.
2183         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2184         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2185         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2186         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2187         let chanmon_cfgs = create_chanmon_cfgs(2);
2188         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2189         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2190         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2191         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2192         let logger = test_utils::TestLogger::new();
2193
2194         let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2195         // Route the first two HTLCs.
2196         let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
2197         let (payment_preimage_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
2198
2199         // Start routing the third HTLC (this is just used to get everyone in the right state).
2200         let (payment_preimage_3, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
2201         let send_1 = {
2202                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
2203                 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();
2204                 nodes[0].node.send_payment(&route, payment_hash_3, &None).unwrap();
2205                 check_added_monitors!(nodes[0], 1);
2206                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2207                 assert_eq!(events.len(), 1);
2208                 SendEvent::from_event(events.remove(0))
2209         };
2210
2211         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2212         // initial fulfill/CS.
2213         assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000));
2214         check_added_monitors!(nodes[1], 1);
2215         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2216
2217         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2218         // remove the second HTLC when we send the HTLC back from B to A.
2219         assert!(nodes[1].node.claim_funds(payment_preimage_2, &None, 20000));
2220         check_added_monitors!(nodes[1], 1);
2221         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2222
2223         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2224         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2225         check_added_monitors!(nodes[0], 1);
2226         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2227         expect_payment_sent!(nodes[0], payment_preimage_1);
2228
2229         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2230         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2231         check_added_monitors!(nodes[1], 1);
2232         // B is already AwaitingRAA, so cant generate a CS here
2233         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2234
2235         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2236         check_added_monitors!(nodes[1], 1);
2237         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2238
2239         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2240         check_added_monitors!(nodes[0], 1);
2241         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2242
2243         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2244         check_added_monitors!(nodes[1], 1);
2245         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2246
2247         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2248         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2249         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2250         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2251         // on-chain as necessary).
2252         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2253         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2254         check_added_monitors!(nodes[0], 1);
2255         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2256         expect_payment_sent!(nodes[0], payment_preimage_2);
2257
2258         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2259         check_added_monitors!(nodes[1], 1);
2260         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2261
2262         expect_pending_htlcs_forwardable!(nodes[1]);
2263         expect_payment_received!(nodes[1], payment_hash_3, 100000);
2264
2265         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2266         // resolve the second HTLC from A's point of view.
2267         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2268         check_added_monitors!(nodes[0], 1);
2269         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2270
2271         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2272         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2273         let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[1]);
2274         let send_2 = {
2275                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
2276                 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();
2277                 nodes[1].node.send_payment(&route, payment_hash_4, &None).unwrap();
2278                 check_added_monitors!(nodes[1], 1);
2279                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2280                 assert_eq!(events.len(), 1);
2281                 SendEvent::from_event(events.remove(0))
2282         };
2283
2284         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2285         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2286         check_added_monitors!(nodes[0], 1);
2287         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2288
2289         // Now just resolve all the outstanding messages/HTLCs for completeness...
2290
2291         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2292         check_added_monitors!(nodes[1], 1);
2293         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2294
2295         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2296         check_added_monitors!(nodes[1], 1);
2297
2298         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2299         check_added_monitors!(nodes[0], 1);
2300         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2301
2302         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2303         check_added_monitors!(nodes[1], 1);
2304         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2305
2306         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2307         check_added_monitors!(nodes[0], 1);
2308
2309         expect_pending_htlcs_forwardable!(nodes[0]);
2310         expect_payment_received!(nodes[0], payment_hash_4, 10000);
2311
2312         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4, 10_000);
2313         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3, 100_000);
2314 }
2315
2316 #[test]
2317 fn channel_monitor_network_test() {
2318         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2319         // tests that ChannelMonitor is able to recover from various states.
2320         let chanmon_cfgs = create_chanmon_cfgs(5);
2321         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2322         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2323         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2324
2325         // Create some initial channels
2326         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2327         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2328         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2329         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2330
2331         // Rebalance the network a bit by relaying one payment through all the channels...
2332         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2333         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2334         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2335         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2336
2337         // Simple case with no pending HTLCs:
2338         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2339         check_added_monitors!(nodes[1], 1);
2340         {
2341                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2342                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2343                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
2344                 check_added_monitors!(nodes[0], 1);
2345                 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2346         }
2347         get_announce_close_broadcast_events(&nodes, 0, 1);
2348         assert_eq!(nodes[0].node.list_channels().len(), 0);
2349         assert_eq!(nodes[1].node.list_channels().len(), 1);
2350
2351         // One pending HTLC is discarded by the force-close:
2352         let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2353
2354         // Simple case of one pending HTLC to HTLC-Timeout
2355         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2356         check_added_monitors!(nodes[1], 1);
2357         {
2358                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2359                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2360                 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
2361                 check_added_monitors!(nodes[2], 1);
2362                 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2363         }
2364         get_announce_close_broadcast_events(&nodes, 1, 2);
2365         assert_eq!(nodes[1].node.list_channels().len(), 0);
2366         assert_eq!(nodes[2].node.list_channels().len(), 1);
2367
2368         macro_rules! claim_funds {
2369                 ($node: expr, $prev_node: expr, $preimage: expr, $amount: expr) => {
2370                         {
2371                                 assert!($node.node.claim_funds($preimage, &None, $amount));
2372                                 check_added_monitors!($node, 1);
2373
2374                                 let events = $node.node.get_and_clear_pending_msg_events();
2375                                 assert_eq!(events.len(), 1);
2376                                 match events[0] {
2377                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2378                                                 assert!(update_add_htlcs.is_empty());
2379                                                 assert!(update_fail_htlcs.is_empty());
2380                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2381                                         },
2382                                         _ => panic!("Unexpected event"),
2383                                 };
2384                         }
2385                 }
2386         }
2387
2388         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2389         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2390         nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2391         check_added_monitors!(nodes[2], 1);
2392         let node2_commitment_txid;
2393         {
2394                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2395                 node2_commitment_txid = node_txn[0].txid();
2396
2397                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2398                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, 3_000_000);
2399
2400                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2401                 nodes[3].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
2402                 check_added_monitors!(nodes[3], 1);
2403
2404                 check_preimage_claim(&nodes[3], &node_txn);
2405         }
2406         get_announce_close_broadcast_events(&nodes, 2, 3);
2407         assert_eq!(nodes[2].node.list_channels().len(), 0);
2408         assert_eq!(nodes[3].node.list_channels().len(), 1);
2409
2410         { // Cheat and reset nodes[4]'s height to 1
2411                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2412                 nodes[4].block_notifier.block_connected(&Block { header, txdata: vec![] }, 1);
2413         }
2414
2415         assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
2416         assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
2417         // One pending HTLC to time out:
2418         let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2419         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2420         // buffer space).
2421
2422         let (close_chan_update_1, close_chan_update_2) = {
2423                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2424                 nodes[3].block_notifier.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
2425                 for i in 3..TEST_FINAL_CLTV + 2 + LATENCY_GRACE_PERIOD_BLOCKS + 1 {
2426                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2427                         nodes[3].block_notifier.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
2428                 }
2429                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2430                 assert_eq!(events.len(), 1);
2431                 let close_chan_update_1 = match events[0] {
2432                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2433                                 msg.clone()
2434                         },
2435                         _ => panic!("Unexpected event"),
2436                 };
2437                 check_added_monitors!(nodes[3], 1);
2438
2439                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2440                 {
2441                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2442                         node_txn.retain(|tx| {
2443                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2444                                         false
2445                                 } else { true }
2446                         });
2447                 }
2448
2449                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2450
2451                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2452                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, 3_000_000);
2453
2454                 header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2455
2456                 nodes[4].block_notifier.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
2457                 for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
2458                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2459                         nodes[4].block_notifier.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
2460                 }
2461                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2462                 assert_eq!(events.len(), 1);
2463                 let close_chan_update_2 = match events[0] {
2464                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2465                                 msg.clone()
2466                         },
2467                         _ => panic!("Unexpected event"),
2468                 };
2469                 check_added_monitors!(nodes[4], 1);
2470                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2471
2472                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2473                 nodes[4].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, TEST_FINAL_CLTV - 5);
2474
2475                 check_preimage_claim(&nodes[4], &node_txn);
2476                 (close_chan_update_1, close_chan_update_2)
2477         };
2478         nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2479         nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2480         assert_eq!(nodes[3].node.list_channels().len(), 0);
2481         assert_eq!(nodes[4].node.list_channels().len(), 0);
2482 }
2483
2484 #[test]
2485 fn test_justice_tx() {
2486         // Test justice txn built on revoked HTLC-Success tx, against both sides
2487         let mut alice_config = UserConfig::default();
2488         alice_config.channel_options.announced_channel = true;
2489         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2490         alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2491         let mut bob_config = UserConfig::default();
2492         bob_config.channel_options.announced_channel = true;
2493         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2494         bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2495         let user_cfgs = [Some(alice_config), Some(bob_config)];
2496         let chanmon_cfgs = create_chanmon_cfgs(2);
2497         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2498         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2499         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2500         // Create some new channels:
2501         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2502
2503         // A pending HTLC which will be revoked:
2504         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2505         // Get the will-be-revoked local txn from nodes[0]
2506         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2507         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2508         assert_eq!(revoked_local_txn[0].input.len(), 1);
2509         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2510         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2511         assert_eq!(revoked_local_txn[1].input.len(), 1);
2512         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2513         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2514         // Revoke the old state
2515         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 3_000_000);
2516
2517         {
2518                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2519                 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2520                 {
2521                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2522                         assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2523                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2524
2525                         check_spends!(node_txn[0], revoked_local_txn[0]);
2526                         node_txn.swap_remove(0);
2527                         node_txn.truncate(1);
2528                 }
2529                 check_added_monitors!(nodes[1], 1);
2530                 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2531
2532                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2533                 // Verify broadcast of revoked HTLC-timeout
2534                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2535                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2536                 check_added_monitors!(nodes[0], 1);
2537                 // Broadcast revoked HTLC-timeout on node 1
2538                 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2539                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2540         }
2541         get_announce_close_broadcast_events(&nodes, 0, 1);
2542
2543         assert_eq!(nodes[0].node.list_channels().len(), 0);
2544         assert_eq!(nodes[1].node.list_channels().len(), 0);
2545
2546         // We test justice_tx build by A on B's revoked HTLC-Success tx
2547         // Create some new channels:
2548         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2549         {
2550                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2551                 node_txn.clear();
2552         }
2553
2554         // A pending HTLC which will be revoked:
2555         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2556         // Get the will-be-revoked local txn from B
2557         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2558         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2559         assert_eq!(revoked_local_txn[0].input.len(), 1);
2560         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2561         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2562         // Revoke the old state
2563         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4, 3_000_000);
2564         {
2565                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2566                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2567                 {
2568                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2569                         assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2570                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2571
2572                         check_spends!(node_txn[0], revoked_local_txn[0]);
2573                         node_txn.swap_remove(0);
2574                 }
2575                 check_added_monitors!(nodes[0], 1);
2576                 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2577
2578                 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2579                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2580                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2581                 check_added_monitors!(nodes[1], 1);
2582                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2583                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2584         }
2585         get_announce_close_broadcast_events(&nodes, 0, 1);
2586         assert_eq!(nodes[0].node.list_channels().len(), 0);
2587         assert_eq!(nodes[1].node.list_channels().len(), 0);
2588 }
2589
2590 #[test]
2591 fn revoked_output_claim() {
2592         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2593         // transaction is broadcast by its counterparty
2594         let chanmon_cfgs = create_chanmon_cfgs(2);
2595         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2596         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2597         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2598         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2599         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2600         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2601         assert_eq!(revoked_local_txn.len(), 1);
2602         // Only output is the full channel value back to nodes[0]:
2603         assert_eq!(revoked_local_txn[0].output.len(), 1);
2604         // Send a payment through, updating everyone's latest commitment txn
2605         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000, 5_000_000);
2606
2607         // Inform nodes[1] that nodes[0] broadcast a stale tx
2608         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2609         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2610         check_added_monitors!(nodes[1], 1);
2611         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2612         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2613
2614         check_spends!(node_txn[0], revoked_local_txn[0]);
2615         check_spends!(node_txn[1], chan_1.3);
2616
2617         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2618         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2619         get_announce_close_broadcast_events(&nodes, 0, 1);
2620         check_added_monitors!(nodes[0], 1)
2621 }
2622
2623 #[test]
2624 fn claim_htlc_outputs_shared_tx() {
2625         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2626         let chanmon_cfgs = create_chanmon_cfgs(2);
2627         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2628         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2629         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2630
2631         // Create some new channel:
2632         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2633
2634         // Rebalance the network to generate htlc in the two directions
2635         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2636         // 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
2637         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2638         let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2639
2640         // Get the will-be-revoked local txn from node[0]
2641         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2642         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2643         assert_eq!(revoked_local_txn[0].input.len(), 1);
2644         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2645         assert_eq!(revoked_local_txn[1].input.len(), 1);
2646         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2647         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2648         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2649
2650         //Revoke the old state
2651         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2652
2653         {
2654                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2655                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2656                 check_added_monitors!(nodes[0], 1);
2657                 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2658                 check_added_monitors!(nodes[1], 1);
2659                 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
2660                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2661
2662                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2663                 assert_eq!(node_txn.len(), 3); // ChannelMonitor: penalty tx, ChannelManager: local commitment + HTLC-timeout
2664
2665                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2666                 check_spends!(node_txn[0], revoked_local_txn[0]);
2667
2668                 let mut witness_lens = BTreeSet::new();
2669                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2670                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2671                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2672                 assert_eq!(witness_lens.len(), 3);
2673                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2674                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2675                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2676
2677                 // Next nodes[1] broadcasts its current local tx state:
2678                 assert_eq!(node_txn[1].input.len(), 1);
2679                 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2680
2681                 assert_eq!(node_txn[2].input.len(), 1);
2682                 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
2683                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2684                 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
2685                 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
2686                 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
2687         }
2688         get_announce_close_broadcast_events(&nodes, 0, 1);
2689         assert_eq!(nodes[0].node.list_channels().len(), 0);
2690         assert_eq!(nodes[1].node.list_channels().len(), 0);
2691 }
2692
2693 #[test]
2694 fn claim_htlc_outputs_single_tx() {
2695         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2696         let chanmon_cfgs = create_chanmon_cfgs(2);
2697         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2698         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2699         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2700
2701         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2702
2703         // Rebalance the network to generate htlc in the two directions
2704         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2705         // 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
2706         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2707         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2708         let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2709
2710         // Get the will-be-revoked local txn from node[0]
2711         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2712
2713         //Revoke the old state
2714         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2715
2716         {
2717                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2718                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2719                 check_added_monitors!(nodes[0], 1);
2720                 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2721                 check_added_monitors!(nodes[1], 1);
2722                 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
2723
2724                 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 200, true, header.block_hash());
2725                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2726
2727                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2728                 assert_eq!(node_txn.len(), 9);
2729                 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2730                 // ChannelManager: local commmitment + local HTLC-timeout (2)
2731                 // 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)
2732                 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2733
2734                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2735                 assert_eq!(node_txn[2].input.len(), 1);
2736                 check_spends!(node_txn[2], chan_1.3);
2737                 assert_eq!(node_txn[3].input.len(), 1);
2738                 let witness_script = node_txn[3].input[0].witness.last().unwrap();
2739                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2740                 check_spends!(node_txn[3], node_txn[2]);
2741
2742                 // Justice transactions are indices 1-2-4
2743                 assert_eq!(node_txn[0].input.len(), 1);
2744                 assert_eq!(node_txn[1].input.len(), 1);
2745                 assert_eq!(node_txn[4].input.len(), 1);
2746
2747                 check_spends!(node_txn[0], revoked_local_txn[0]);
2748                 check_spends!(node_txn[1], revoked_local_txn[0]);
2749                 check_spends!(node_txn[4], revoked_local_txn[0]);
2750
2751                 let mut witness_lens = BTreeSet::new();
2752                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2753                 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2754                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2755                 assert_eq!(witness_lens.len(), 3);
2756                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2757                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2758                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2759         }
2760         get_announce_close_broadcast_events(&nodes, 0, 1);
2761         assert_eq!(nodes[0].node.list_channels().len(), 0);
2762         assert_eq!(nodes[1].node.list_channels().len(), 0);
2763 }
2764
2765 #[test]
2766 fn test_htlc_on_chain_success() {
2767         // Test that in case of a unilateral close onchain, we detect the state of output thanks to
2768         // ChainWatchInterface and pass the preimage backward accordingly. So here we test that ChannelManager is
2769         // broadcasting the right event to other nodes in payment path.
2770         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2771         // A --------------------> B ----------------------> C (preimage)
2772         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2773         // commitment transaction was broadcast.
2774         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2775         // towards B.
2776         // B should be able to claim via preimage if A then broadcasts its local tx.
2777         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2778         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2779         // PaymentSent event).
2780
2781         let chanmon_cfgs = create_chanmon_cfgs(3);
2782         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2783         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2784         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2785
2786         // Create some initial channels
2787         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2788         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2789
2790         // Rebalance the network a bit by relaying one payment through all the channels...
2791         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2792         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2793
2794         let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2795         let (our_payment_preimage_2, _payment_hash_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2796         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2797
2798         // Broadcast legit commitment tx from C on B's chain
2799         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2800         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2801         assert_eq!(commitment_tx.len(), 1);
2802         check_spends!(commitment_tx[0], chan_2.3);
2803         nodes[2].node.claim_funds(our_payment_preimage, &None, 3_000_000);
2804         nodes[2].node.claim_funds(our_payment_preimage_2, &None, 3_000_000);
2805         check_added_monitors!(nodes[2], 2);
2806         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2807         assert!(updates.update_add_htlcs.is_empty());
2808         assert!(updates.update_fail_htlcs.is_empty());
2809         assert!(updates.update_fail_malformed_htlcs.is_empty());
2810         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2811
2812         nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2813         check_closed_broadcast!(nodes[2], false);
2814         check_added_monitors!(nodes[2], 1);
2815         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)
2816         assert_eq!(node_txn.len(), 5);
2817         assert_eq!(node_txn[0], node_txn[3]);
2818         assert_eq!(node_txn[1], node_txn[4]);
2819         assert_eq!(node_txn[2], commitment_tx[0]);
2820         check_spends!(node_txn[0], commitment_tx[0]);
2821         check_spends!(node_txn[1], commitment_tx[0]);
2822         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2823         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2824         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2825         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2826         assert_eq!(node_txn[0].lock_time, 0);
2827         assert_eq!(node_txn[1].lock_time, 0);
2828
2829         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2830         nodes[1].block_notifier.block_connected(&Block { header, txdata: node_txn}, 1);
2831         {
2832                 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
2833                 assert_eq!(added_monitors.len(), 1);
2834                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2835                 added_monitors.clear();
2836         }
2837         let events = nodes[1].node.get_and_clear_pending_msg_events();
2838         {
2839                 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
2840                 assert_eq!(added_monitors.len(), 2);
2841                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2842                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2843                 added_monitors.clear();
2844         }
2845         assert_eq!(events.len(), 2);
2846         match events[0] {
2847                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2848                 _ => panic!("Unexpected event"),
2849         }
2850         match events[1] {
2851                 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, .. } } => {
2852                         assert!(update_add_htlcs.is_empty());
2853                         assert!(update_fail_htlcs.is_empty());
2854                         assert_eq!(update_fulfill_htlcs.len(), 1);
2855                         assert!(update_fail_malformed_htlcs.is_empty());
2856                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2857                 },
2858                 _ => panic!("Unexpected event"),
2859         };
2860         macro_rules! check_tx_local_broadcast {
2861                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2862                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2863                         assert_eq!(node_txn.len(), 5);
2864                         // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2865                         // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2866                         check_spends!(node_txn[0], $commitment_tx);
2867                         check_spends!(node_txn[1], $commitment_tx);
2868                         assert_ne!(node_txn[0].lock_time, 0);
2869                         assert_ne!(node_txn[1].lock_time, 0);
2870                         if $htlc_offered {
2871                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2872                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2873                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2874                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2875                         } else {
2876                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2877                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2878                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2879                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2880                         }
2881                         check_spends!(node_txn[2], $chan_tx);
2882                         check_spends!(node_txn[3], node_txn[2]);
2883                         check_spends!(node_txn[4], node_txn[2]);
2884                         assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), 71);
2885                         assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2886                         assert_eq!(node_txn[4].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2887                         assert!(node_txn[3].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2888                         assert!(node_txn[4].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2889                         assert_ne!(node_txn[3].lock_time, 0);
2890                         assert_ne!(node_txn[4].lock_time, 0);
2891                         node_txn.clear();
2892                 } }
2893         }
2894         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2895         // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2896         // timeout-claim of the output that nodes[2] just claimed via success.
2897         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2898
2899         // Broadcast legit commitment tx from A on B's chain
2900         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2901         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2902         check_spends!(commitment_tx[0], chan_1.3);
2903         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2904         check_closed_broadcast!(nodes[1], false);
2905         check_added_monitors!(nodes[1], 1);
2906         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 1 (HTLC-Success)
2907         assert_eq!(node_txn.len(), 4);
2908         check_spends!(node_txn[0], commitment_tx[0]);
2909         assert_eq!(node_txn[0].input.len(), 2);
2910         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2911         assert_eq!(node_txn[0].input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2912         assert_eq!(node_txn[0].lock_time, 0);
2913         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2914         check_spends!(node_txn[1], chan_1.3);
2915         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
2916         check_spends!(node_txn[2], node_txn[1]);
2917         check_spends!(node_txn[3], node_txn[1]);
2918         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2919         // we already checked the same situation with A.
2920
2921         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2922         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
2923         check_closed_broadcast!(nodes[0], false);
2924         check_added_monitors!(nodes[0], 1);
2925         let events = nodes[0].node.get_and_clear_pending_events();
2926         assert_eq!(events.len(), 2);
2927         let mut first_claimed = false;
2928         for event in events {
2929                 match event {
2930                         Event::PaymentSent { payment_preimage } => {
2931                                 if payment_preimage == our_payment_preimage {
2932                                         assert!(!first_claimed);
2933                                         first_claimed = true;
2934                                 } else {
2935                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2936                                 }
2937                         },
2938                         _ => panic!("Unexpected event"),
2939                 }
2940         }
2941         check_tx_local_broadcast!(nodes[0], true, commitment_tx[0], chan_1.3);
2942 }
2943
2944 #[test]
2945 fn test_htlc_on_chain_timeout() {
2946         // Test that in case of a unilateral close onchain, we detect the state of output thanks to
2947         // ChainWatchInterface and timeout the HTLC backward accordingly. So here we test that ChannelManager is
2948         // broadcasting the right event to other nodes in payment path.
2949         // A ------------------> B ----------------------> C (timeout)
2950         //    B's commitment tx                 C's commitment tx
2951         //            \                                  \
2952         //         B's HTLC timeout tx               B's timeout tx
2953
2954         let chanmon_cfgs = create_chanmon_cfgs(3);
2955         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2956         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2957         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2958
2959         // Create some intial channels
2960         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2961         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2962
2963         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2964         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2965         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2966
2967         let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2968         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2969
2970         // Broadcast legit commitment tx from C on B's chain
2971         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2972         check_spends!(commitment_tx[0], chan_2.3);
2973         nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
2974         check_added_monitors!(nodes[2], 0);
2975         expect_pending_htlcs_forwardable!(nodes[2]);
2976         check_added_monitors!(nodes[2], 1);
2977
2978         let events = nodes[2].node.get_and_clear_pending_msg_events();
2979         assert_eq!(events.len(), 1);
2980         match events[0] {
2981                 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, .. } } => {
2982                         assert!(update_add_htlcs.is_empty());
2983                         assert!(!update_fail_htlcs.is_empty());
2984                         assert!(update_fulfill_htlcs.is_empty());
2985                         assert!(update_fail_malformed_htlcs.is_empty());
2986                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2987                 },
2988                 _ => panic!("Unexpected event"),
2989         };
2990         nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2991         check_closed_broadcast!(nodes[2], false);
2992         check_added_monitors!(nodes[2], 1);
2993         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2994         assert_eq!(node_txn.len(), 1);
2995         check_spends!(node_txn[0], chan_2.3);
2996         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2997
2998         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2999         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
3000         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
3001         let timeout_tx;
3002         {
3003                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3004                 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
3005                 assert_eq!(node_txn[1], node_txn[3]);
3006                 assert_eq!(node_txn[2], node_txn[4]);
3007
3008                 check_spends!(node_txn[0], commitment_tx[0]);
3009                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3010
3011                 check_spends!(node_txn[1], chan_2.3);
3012                 check_spends!(node_txn[2], node_txn[1]);
3013                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
3014                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3015
3016                 timeout_tx = node_txn[0].clone();
3017                 node_txn.clear();
3018         }
3019
3020         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![timeout_tx]}, 1);
3021         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
3022         check_added_monitors!(nodes[1], 1);
3023         check_closed_broadcast!(nodes[1], false);
3024
3025         expect_pending_htlcs_forwardable!(nodes[1]);
3026         check_added_monitors!(nodes[1], 1);
3027         let events = nodes[1].node.get_and_clear_pending_msg_events();
3028         assert_eq!(events.len(), 1);
3029         match events[0] {
3030                 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, .. } } => {
3031                         assert!(update_add_htlcs.is_empty());
3032                         assert!(!update_fail_htlcs.is_empty());
3033                         assert!(update_fulfill_htlcs.is_empty());
3034                         assert!(update_fail_malformed_htlcs.is_empty());
3035                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3036                 },
3037                 _ => panic!("Unexpected event"),
3038         };
3039         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
3040         assert_eq!(node_txn.len(), 0);
3041
3042         // Broadcast legit commitment tx from B on A's chain
3043         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3044         check_spends!(commitment_tx[0], chan_1.3);
3045
3046         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
3047         check_closed_broadcast!(nodes[0], false);
3048         check_added_monitors!(nodes[0], 1);
3049         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 1 timeout tx
3050         assert_eq!(node_txn.len(), 3);
3051         check_spends!(node_txn[0], commitment_tx[0]);
3052         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3053         check_spends!(node_txn[1], chan_1.3);
3054         check_spends!(node_txn[2], node_txn[1]);
3055         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
3056         assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3057 }
3058
3059 #[test]
3060 fn test_simple_commitment_revoked_fail_backward() {
3061         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3062         // and fail backward accordingly.
3063
3064         let chanmon_cfgs = create_chanmon_cfgs(3);
3065         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3066         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3067         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3068
3069         // Create some initial channels
3070         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3071         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3072
3073         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3074         // Get the will-be-revoked local txn from nodes[2]
3075         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3076         // Revoke the old state
3077         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, 3_000_000);
3078
3079         let (_, payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3080
3081         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
3082         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3083         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
3084         check_added_monitors!(nodes[1], 1);
3085         check_closed_broadcast!(nodes[1], false);
3086
3087         expect_pending_htlcs_forwardable!(nodes[1]);
3088         check_added_monitors!(nodes[1], 1);
3089         let events = nodes[1].node.get_and_clear_pending_msg_events();
3090         assert_eq!(events.len(), 1);
3091         match events[0] {
3092                 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, .. } } => {
3093                         assert!(update_add_htlcs.is_empty());
3094                         assert_eq!(update_fail_htlcs.len(), 1);
3095                         assert!(update_fulfill_htlcs.is_empty());
3096                         assert!(update_fail_malformed_htlcs.is_empty());
3097                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3098
3099                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3100                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3101
3102                         let events = nodes[0].node.get_and_clear_pending_msg_events();
3103                         assert_eq!(events.len(), 1);
3104                         match events[0] {
3105                                 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3106                                 _ => panic!("Unexpected event"),
3107                         }
3108                         expect_payment_failed!(nodes[0], payment_hash, false);
3109                 },
3110                 _ => panic!("Unexpected event"),
3111         }
3112 }
3113
3114 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3115         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3116         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3117         // commitment transaction anymore.
3118         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3119         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3120         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3121         // technically disallowed and we should probably handle it reasonably.
3122         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3123         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3124         // transactions:
3125         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3126         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3127         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3128         //   and once they revoke the previous commitment transaction (allowing us to send a new
3129         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3130         let chanmon_cfgs = create_chanmon_cfgs(3);
3131         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3132         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3133         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3134
3135         // Create some initial channels
3136         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3137         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3138
3139         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3140         // Get the will-be-revoked local txn from nodes[2]
3141         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3142         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3143         // Revoke the old state
3144         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, if no_to_remote { 10_000 } else { 3_000_000});
3145
3146         let value = if use_dust {
3147                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3148                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3149                 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3150         } else { 3000000 };
3151
3152         let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3153         let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3154         let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3155
3156         assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, &None));
3157         expect_pending_htlcs_forwardable!(nodes[2]);
3158         check_added_monitors!(nodes[2], 1);
3159         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3160         assert!(updates.update_add_htlcs.is_empty());
3161         assert!(updates.update_fulfill_htlcs.is_empty());
3162         assert!(updates.update_fail_malformed_htlcs.is_empty());
3163         assert_eq!(updates.update_fail_htlcs.len(), 1);
3164         assert!(updates.update_fee.is_none());
3165         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3166         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3167         // Drop the last RAA from 3 -> 2
3168
3169         assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, &None));
3170         expect_pending_htlcs_forwardable!(nodes[2]);
3171         check_added_monitors!(nodes[2], 1);
3172         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3173         assert!(updates.update_add_htlcs.is_empty());
3174         assert!(updates.update_fulfill_htlcs.is_empty());
3175         assert!(updates.update_fail_malformed_htlcs.is_empty());
3176         assert_eq!(updates.update_fail_htlcs.len(), 1);
3177         assert!(updates.update_fee.is_none());
3178         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
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 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         assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, &None));
3187         expect_pending_htlcs_forwardable!(nodes[2]);
3188         check_added_monitors!(nodes[2], 1);
3189         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3190         assert!(updates.update_add_htlcs.is_empty());
3191         assert!(updates.update_fulfill_htlcs.is_empty());
3192         assert!(updates.update_fail_malformed_htlcs.is_empty());
3193         assert_eq!(updates.update_fail_htlcs.len(), 1);
3194         assert!(updates.update_fee.is_none());
3195         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3196         // At this point first_payment_hash has dropped out of the latest two commitment
3197         // transactions that nodes[1] is tracking...
3198         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3199         check_added_monitors!(nodes[1], 1);
3200         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3201         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3202         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3203         check_added_monitors!(nodes[2], 1);
3204
3205         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3206         // on nodes[2]'s RAA.
3207         let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3208         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3209         let logger = test_utils::TestLogger::new();
3210         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();
3211         nodes[1].node.send_payment(&route, fourth_payment_hash, &None).unwrap();
3212         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3213         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3214         check_added_monitors!(nodes[1], 0);
3215
3216         if deliver_bs_raa {
3217                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3218                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3219                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3220                 check_added_monitors!(nodes[1], 1);
3221                 let events = nodes[1].node.get_and_clear_pending_events();
3222                 assert_eq!(events.len(), 1);
3223                 match events[0] {
3224                         Event::PendingHTLCsForwardable { .. } => { },
3225                         _ => panic!("Unexpected event"),
3226                 };
3227                 // Deliberately don't process the pending fail-back so they all fail back at once after
3228                 // block connection just like the !deliver_bs_raa case
3229         }
3230
3231         let mut failed_htlcs = HashSet::new();
3232         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3233
3234         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
3235         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3236         check_added_monitors!(nodes[1], 1);
3237         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
3238
3239         let events = nodes[1].node.get_and_clear_pending_events();
3240         assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
3241         match events[0] {
3242                 Event::PaymentFailed { ref payment_hash, .. } => {
3243                         assert_eq!(*payment_hash, fourth_payment_hash);
3244                 },
3245                 _ => panic!("Unexpected event"),
3246         }
3247         if !deliver_bs_raa {
3248                 match events[1] {
3249                         Event::PendingHTLCsForwardable { .. } => { },
3250                         _ => panic!("Unexpected event"),
3251                 };
3252         }
3253         nodes[1].node.process_pending_htlc_forwards();
3254         check_added_monitors!(nodes[1], 1);
3255
3256         let events = nodes[1].node.get_and_clear_pending_msg_events();
3257         assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
3258         match events[if deliver_bs_raa { 1 } else { 0 }] {
3259                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3260                 _ => panic!("Unexpected event"),
3261         }
3262         if deliver_bs_raa {
3263                 match events[0] {
3264                         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, .. } } => {
3265                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3266                                 assert_eq!(update_add_htlcs.len(), 1);
3267                                 assert!(update_fulfill_htlcs.is_empty());
3268                                 assert!(update_fail_htlcs.is_empty());
3269                                 assert!(update_fail_malformed_htlcs.is_empty());
3270                         },
3271                         _ => panic!("Unexpected event"),
3272                 }
3273         }
3274         match events[if deliver_bs_raa { 2 } else { 1 }] {
3275                 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, .. } } => {
3276                         assert!(update_add_htlcs.is_empty());
3277                         assert_eq!(update_fail_htlcs.len(), 3);
3278                         assert!(update_fulfill_htlcs.is_empty());
3279                         assert!(update_fail_malformed_htlcs.is_empty());
3280                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3281
3282                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3283                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3284                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3285
3286                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3287
3288                         let events = nodes[0].node.get_and_clear_pending_msg_events();
3289                         // If we delivered B's RAA we got an unknown preimage error, not something
3290                         // that we should update our routing table for.
3291                         assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
3292                         for event in events {
3293                                 match event {
3294                                         MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3295                                         _ => panic!("Unexpected event"),
3296                                 }
3297                         }
3298                         let events = nodes[0].node.get_and_clear_pending_events();
3299                         assert_eq!(events.len(), 3);
3300                         match events[0] {
3301                                 Event::PaymentFailed { ref payment_hash, .. } => {
3302                                         assert!(failed_htlcs.insert(payment_hash.0));
3303                                 },
3304                                 _ => panic!("Unexpected event"),
3305                         }
3306                         match events[1] {
3307                                 Event::PaymentFailed { ref payment_hash, .. } => {
3308                                         assert!(failed_htlcs.insert(payment_hash.0));
3309                                 },
3310                                 _ => panic!("Unexpected event"),
3311                         }
3312                         match events[2] {
3313                                 Event::PaymentFailed { ref payment_hash, .. } => {
3314                                         assert!(failed_htlcs.insert(payment_hash.0));
3315                                 },
3316                                 _ => panic!("Unexpected event"),
3317                         }
3318                 },
3319                 _ => panic!("Unexpected event"),
3320         }
3321
3322         assert!(failed_htlcs.contains(&first_payment_hash.0));
3323         assert!(failed_htlcs.contains(&second_payment_hash.0));
3324         assert!(failed_htlcs.contains(&third_payment_hash.0));
3325 }
3326
3327 #[test]
3328 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3329         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3330         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3331         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3332         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3333 }
3334
3335 #[test]
3336 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3337         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3338         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3339         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3340         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3341 }
3342
3343 #[test]
3344 fn fail_backward_pending_htlc_upon_channel_failure() {
3345         let chanmon_cfgs = create_chanmon_cfgs(2);
3346         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3347         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3348         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3349         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3350         let logger = test_utils::TestLogger::new();
3351
3352         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3353         {
3354                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
3355                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3356                 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();
3357                 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
3358                 check_added_monitors!(nodes[0], 1);
3359
3360                 let payment_event = {
3361                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3362                         assert_eq!(events.len(), 1);
3363                         SendEvent::from_event(events.remove(0))
3364                 };
3365                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3366                 assert_eq!(payment_event.msgs.len(), 1);
3367         }
3368
3369         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3370         let (_, failed_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3371         {
3372                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3373                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3374                 nodes[0].node.send_payment(&route, failed_payment_hash, &None).unwrap();
3375                 check_added_monitors!(nodes[0], 0);
3376
3377                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3378         }
3379
3380         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3381         {
3382                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[1]);
3383
3384                 let secp_ctx = Secp256k1::new();
3385                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3386                 let current_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
3387                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3388                 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();
3389                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &None, current_height).unwrap();
3390                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3391                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3392
3393                 // Send a 0-msat update_add_htlc to fail the channel.
3394                 let update_add_htlc = msgs::UpdateAddHTLC {
3395                         channel_id: chan.2,
3396                         htlc_id: 0,
3397                         amount_msat: 0,
3398                         payment_hash,
3399                         cltv_expiry,
3400                         onion_routing_packet,
3401                 };
3402                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3403         }
3404
3405         // Check that Alice fails backward the pending HTLC from the second payment.
3406         expect_payment_failed!(nodes[0], failed_payment_hash, true);
3407         check_closed_broadcast!(nodes[0], true);
3408         check_added_monitors!(nodes[0], 1);
3409 }
3410
3411 #[test]
3412 fn test_htlc_ignore_latest_remote_commitment() {
3413         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3414         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3415         let chanmon_cfgs = create_chanmon_cfgs(2);
3416         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3417         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3418         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3419         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3420
3421         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3422         nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
3423         check_closed_broadcast!(nodes[0], false);
3424         check_added_monitors!(nodes[0], 1);
3425
3426         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3427         assert_eq!(node_txn.len(), 2);
3428
3429         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3430         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3431         check_closed_broadcast!(nodes[1], false);
3432         check_added_monitors!(nodes[1], 1);
3433
3434         // Duplicate the block_connected call since this may happen due to other listeners
3435         // registering new transactions
3436         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3437 }
3438
3439 #[test]
3440 fn test_force_close_fail_back() {
3441         // Check which HTLCs are failed-backwards on channel force-closure
3442         let chanmon_cfgs = create_chanmon_cfgs(3);
3443         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3444         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3445         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3446         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3447         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3448         let logger = test_utils::TestLogger::new();
3449
3450         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3451
3452         let mut payment_event = {
3453                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3454                 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();
3455                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
3456                 check_added_monitors!(nodes[0], 1);
3457
3458                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3459                 assert_eq!(events.len(), 1);
3460                 SendEvent::from_event(events.remove(0))
3461         };
3462
3463         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3464         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3465
3466         expect_pending_htlcs_forwardable!(nodes[1]);
3467
3468         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3469         assert_eq!(events_2.len(), 1);
3470         payment_event = SendEvent::from_event(events_2.remove(0));
3471         assert_eq!(payment_event.msgs.len(), 1);
3472
3473         check_added_monitors!(nodes[1], 1);
3474         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3475         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3476         check_added_monitors!(nodes[2], 1);
3477         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3478
3479         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3480         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3481         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3482
3483         nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
3484         check_closed_broadcast!(nodes[2], false);
3485         check_added_monitors!(nodes[2], 1);
3486         let tx = {
3487                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3488                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3489                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3490                 // back to nodes[1] upon timeout otherwise.
3491                 assert_eq!(node_txn.len(), 1);
3492                 node_txn.remove(0)
3493         };
3494
3495         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3496         nodes[1].block_notifier.block_connected_checked(&header, 1, &[&tx], &[1]);
3497
3498         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3499         check_closed_broadcast!(nodes[1], false);
3500         check_added_monitors!(nodes[1], 1);
3501
3502         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3503         {
3504                 let mut monitors = nodes[2].chan_monitor.simple_monitor.monitors.lock().unwrap();
3505                 monitors.get_mut(&OutPoint{ txid: Txid::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), index: 0 }).unwrap()
3506                         .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
3507         }
3508         nodes[2].block_notifier.block_connected_checked(&header, 1, &[&tx], &[1]);
3509         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3510         assert_eq!(node_txn.len(), 1);
3511         assert_eq!(node_txn[0].input.len(), 1);
3512         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3513         assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3514         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3515
3516         check_spends!(node_txn[0], tx);
3517 }
3518
3519 #[test]
3520 fn test_unconf_chan() {
3521         // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
3522         let chanmon_cfgs = create_chanmon_cfgs(2);
3523         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3524         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3525         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3526         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3527
3528         let channel_state = nodes[0].node.channel_state.lock().unwrap();
3529         assert_eq!(channel_state.by_id.len(), 1);
3530         assert_eq!(channel_state.short_to_id.len(), 1);
3531         mem::drop(channel_state);
3532
3533         let mut headers = Vec::new();
3534         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3535         headers.push(header.clone());
3536         for _i in 2..100 {
3537                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3538                 headers.push(header.clone());
3539         }
3540         let mut height = 99;
3541         while !headers.is_empty() {
3542                 nodes[0].node.block_disconnected(&headers.pop().unwrap(), height);
3543                 height -= 1;
3544         }
3545         check_closed_broadcast!(nodes[0], false);
3546         check_added_monitors!(nodes[0], 1);
3547         let channel_state = nodes[0].node.channel_state.lock().unwrap();
3548         assert_eq!(channel_state.by_id.len(), 0);
3549         assert_eq!(channel_state.short_to_id.len(), 0);
3550 }
3551
3552 #[test]
3553 fn test_simple_peer_disconnect() {
3554         // Test that we can reconnect when there are no lost messages
3555         let chanmon_cfgs = create_chanmon_cfgs(3);
3556         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3557         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3558         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3559         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3560         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
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         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3565
3566         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3567         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3568         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3569         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1, 1_000_000);
3570
3571         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3572         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3573         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3574
3575         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3576         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3577         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3578         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3579
3580         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3581         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3582
3583         claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3, 1_000_000);
3584         fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
3585
3586         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3587         {
3588                 let events = nodes[0].node.get_and_clear_pending_events();
3589                 assert_eq!(events.len(), 2);
3590                 match events[0] {
3591                         Event::PaymentSent { payment_preimage } => {
3592                                 assert_eq!(payment_preimage, payment_preimage_3);
3593                         },
3594                         _ => panic!("Unexpected event"),
3595                 }
3596                 match events[1] {
3597                         Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
3598                                 assert_eq!(payment_hash, payment_hash_5);
3599                                 assert!(rejected_by_dest);
3600                         },
3601                         _ => panic!("Unexpected event"),
3602                 }
3603         }
3604
3605         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4, 1_000_000);
3606         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3607 }
3608
3609 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
3610         // Test that we can reconnect when in-flight HTLC updates get dropped
3611         let chanmon_cfgs = create_chanmon_cfgs(2);
3612         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3613         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3614         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3615         if messages_delivered == 0 {
3616                 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3617                 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3618         } else {
3619                 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3620         }
3621
3622         let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
3623
3624         let logger = test_utils::TestLogger::new();
3625         let payment_event = {
3626                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3627                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3628                         &nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3629                         &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3630                 nodes[0].node.send_payment(&route, payment_hash_1, &None).unwrap();
3631                 check_added_monitors!(nodes[0], 1);
3632
3633                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3634                 assert_eq!(events.len(), 1);
3635                 SendEvent::from_event(events.remove(0))
3636         };
3637         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3638
3639         if messages_delivered < 2 {
3640                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3641         } else {
3642                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3643                 if messages_delivered >= 3 {
3644                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3645                         check_added_monitors!(nodes[1], 1);
3646                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3647
3648                         if messages_delivered >= 4 {
3649                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3650                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3651                                 check_added_monitors!(nodes[0], 1);
3652
3653                                 if messages_delivered >= 5 {
3654                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3655                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3656                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3657                                         check_added_monitors!(nodes[0], 1);
3658
3659                                         if messages_delivered >= 6 {
3660                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3661                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3662                                                 check_added_monitors!(nodes[1], 1);
3663                                         }
3664                                 }
3665                         }
3666                 }
3667         }
3668
3669         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3670         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3671         if messages_delivered < 3 {
3672                 // Even if the funding_locked messages get exchanged, as long as nothing further was
3673                 // received on either side, both sides will need to resend them.
3674                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
3675         } else if messages_delivered == 3 {
3676                 // nodes[0] still wants its RAA + commitment_signed
3677                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
3678         } else if messages_delivered == 4 {
3679                 // nodes[0] still wants its commitment_signed
3680                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3681         } else if messages_delivered == 5 {
3682                 // nodes[1] still wants its final RAA
3683                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3684         } else if messages_delivered == 6 {
3685                 // Everything was delivered...
3686                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3687         }
3688
3689         let events_1 = nodes[1].node.get_and_clear_pending_events();
3690         assert_eq!(events_1.len(), 1);
3691         match events_1[0] {
3692                 Event::PendingHTLCsForwardable { .. } => { },
3693                 _ => panic!("Unexpected event"),
3694         };
3695
3696         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3697         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3698         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3699
3700         nodes[1].node.process_pending_htlc_forwards();
3701
3702         let events_2 = nodes[1].node.get_and_clear_pending_events();
3703         assert_eq!(events_2.len(), 1);
3704         match events_2[0] {
3705                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
3706                         assert_eq!(payment_hash_1, *payment_hash);
3707                         assert_eq!(*payment_secret, None);
3708                         assert_eq!(amt, 1000000);
3709                 },
3710                 _ => panic!("Unexpected event"),
3711         }
3712
3713         nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000);
3714         check_added_monitors!(nodes[1], 1);
3715
3716         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3717         assert_eq!(events_3.len(), 1);
3718         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3719                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3720                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3721                         assert!(updates.update_add_htlcs.is_empty());
3722                         assert!(updates.update_fail_htlcs.is_empty());
3723                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3724                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3725                         assert!(updates.update_fee.is_none());
3726                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3727                 },
3728                 _ => panic!("Unexpected event"),
3729         };
3730
3731         if messages_delivered >= 1 {
3732                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3733
3734                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3735                 assert_eq!(events_4.len(), 1);
3736                 match events_4[0] {
3737                         Event::PaymentSent { ref payment_preimage } => {
3738                                 assert_eq!(payment_preimage_1, *payment_preimage);
3739                         },
3740                         _ => panic!("Unexpected event"),
3741                 }
3742
3743                 if messages_delivered >= 2 {
3744                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3745                         check_added_monitors!(nodes[0], 1);
3746                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3747
3748                         if messages_delivered >= 3 {
3749                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3750                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3751                                 check_added_monitors!(nodes[1], 1);
3752
3753                                 if messages_delivered >= 4 {
3754                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3755                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3756                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3757                                         check_added_monitors!(nodes[1], 1);
3758
3759                                         if messages_delivered >= 5 {
3760                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3761                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3762                                                 check_added_monitors!(nodes[0], 1);
3763                                         }
3764                                 }
3765                         }
3766                 }
3767         }
3768
3769         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3770         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3771         if messages_delivered < 2 {
3772                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
3773                 //TODO: Deduplicate PaymentSent events, then enable this if:
3774                 //if messages_delivered < 1 {
3775                         let events_4 = nodes[0].node.get_and_clear_pending_events();
3776                         assert_eq!(events_4.len(), 1);
3777                         match events_4[0] {
3778                                 Event::PaymentSent { ref payment_preimage } => {
3779                                         assert_eq!(payment_preimage_1, *payment_preimage);
3780                                 },
3781                                 _ => panic!("Unexpected event"),
3782                         }
3783                 //}
3784         } else if messages_delivered == 2 {
3785                 // nodes[0] still wants its RAA + commitment_signed
3786                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
3787         } else if messages_delivered == 3 {
3788                 // nodes[0] still wants its commitment_signed
3789                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
3790         } else if messages_delivered == 4 {
3791                 // nodes[1] still wants its final RAA
3792                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3793         } else if messages_delivered == 5 {
3794                 // Everything was delivered...
3795                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3796         }
3797
3798         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3799         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3800         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3801
3802         // Channel should still work fine...
3803         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3804         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3805                 &nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3806                 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3807         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3808         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3809 }
3810
3811 #[test]
3812 fn test_drop_messages_peer_disconnect_a() {
3813         do_test_drop_messages_peer_disconnect(0);
3814         do_test_drop_messages_peer_disconnect(1);
3815         do_test_drop_messages_peer_disconnect(2);
3816         do_test_drop_messages_peer_disconnect(3);
3817 }
3818
3819 #[test]
3820 fn test_drop_messages_peer_disconnect_b() {
3821         do_test_drop_messages_peer_disconnect(4);
3822         do_test_drop_messages_peer_disconnect(5);
3823         do_test_drop_messages_peer_disconnect(6);
3824 }
3825
3826 #[test]
3827 fn test_funding_peer_disconnect() {
3828         // Test that we can lock in our funding tx while disconnected
3829         let chanmon_cfgs = create_chanmon_cfgs(2);
3830         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3831         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3832         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3833         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3834
3835         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3836         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3837
3838         confirm_transaction(&nodes[0].block_notifier, &nodes[0].chain_monitor, &tx, tx.version);
3839         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3840         assert_eq!(events_1.len(), 1);
3841         match events_1[0] {
3842                 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3843                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3844                 },
3845                 _ => panic!("Unexpected event"),
3846         }
3847
3848         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3849
3850         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3851         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3852
3853         confirm_transaction(&nodes[1].block_notifier, &nodes[1].chain_monitor, &tx, tx.version);
3854         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3855         assert_eq!(events_2.len(), 2);
3856         let funding_locked = match events_2[0] {
3857                 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3858                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3859                         msg.clone()
3860                 },
3861                 _ => panic!("Unexpected event"),
3862         };
3863         let bs_announcement_sigs = match events_2[1] {
3864                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3865                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3866                         msg.clone()
3867                 },
3868                 _ => panic!("Unexpected event"),
3869         };
3870
3871         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3872
3873         nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3874         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3875         let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3876         assert_eq!(events_3.len(), 2);
3877         let as_announcement_sigs = match events_3[0] {
3878                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3879                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3880                         msg.clone()
3881                 },
3882                 _ => panic!("Unexpected event"),
3883         };
3884         let (as_announcement, as_update) = match events_3[1] {
3885                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3886                         (msg.clone(), update_msg.clone())
3887                 },
3888                 _ => panic!("Unexpected event"),
3889         };
3890
3891         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3892         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3893         assert_eq!(events_4.len(), 1);
3894         let (_, bs_update) = match events_4[0] {
3895                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3896                         (msg.clone(), update_msg.clone())
3897                 },
3898                 _ => panic!("Unexpected event"),
3899         };
3900
3901         nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3902         nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3903         nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3904
3905         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3906         let logger = test_utils::TestLogger::new();
3907         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();
3908         let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3909         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage, 1_000_000);
3910 }
3911
3912 #[test]
3913 fn test_drop_messages_peer_disconnect_dual_htlc() {
3914         // Test that we can handle reconnecting when both sides of a channel have pending
3915         // commitment_updates when we disconnect.
3916         let chanmon_cfgs = create_chanmon_cfgs(2);
3917         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3918         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3919         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3920         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3921         let logger = test_utils::TestLogger::new();
3922
3923         let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3924
3925         // Now try to send a second payment which will fail to send
3926         let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
3927         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3928         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();
3929         nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
3930         check_added_monitors!(nodes[0], 1);
3931
3932         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3933         assert_eq!(events_1.len(), 1);
3934         match events_1[0] {
3935                 MessageSendEvent::UpdateHTLCs { .. } => {},
3936                 _ => panic!("Unexpected event"),
3937         }
3938
3939         assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000));
3940         check_added_monitors!(nodes[1], 1);
3941
3942         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3943         assert_eq!(events_2.len(), 1);
3944         match events_2[0] {
3945                 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 } } => {
3946                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3947                         assert!(update_add_htlcs.is_empty());
3948                         assert_eq!(update_fulfill_htlcs.len(), 1);
3949                         assert!(update_fail_htlcs.is_empty());
3950                         assert!(update_fail_malformed_htlcs.is_empty());
3951                         assert!(update_fee.is_none());
3952
3953                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3954                         let events_3 = nodes[0].node.get_and_clear_pending_events();
3955                         assert_eq!(events_3.len(), 1);
3956                         match events_3[0] {
3957                                 Event::PaymentSent { ref payment_preimage } => {
3958                                         assert_eq!(*payment_preimage, payment_preimage_1);
3959                                 },
3960                                 _ => panic!("Unexpected event"),
3961                         }
3962
3963                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3964                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3965                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3966                         check_added_monitors!(nodes[0], 1);
3967                 },
3968                 _ => panic!("Unexpected event"),
3969         }
3970
3971         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3972         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3973
3974         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3975         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3976         assert_eq!(reestablish_1.len(), 1);
3977         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3978         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3979         assert_eq!(reestablish_2.len(), 1);
3980
3981         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3982         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3983         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3984         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3985
3986         assert!(as_resp.0.is_none());
3987         assert!(bs_resp.0.is_none());
3988
3989         assert!(bs_resp.1.is_none());
3990         assert!(bs_resp.2.is_none());
3991
3992         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3993
3994         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3995         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3996         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3997         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3998         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3999         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4000         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4001         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4002         // No commitment_signed so get_event_msg's assert(len == 1) passes
4003         check_added_monitors!(nodes[1], 1);
4004
4005         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4006         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4007         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4008         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4009         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4010         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4011         assert!(bs_second_commitment_signed.update_fee.is_none());
4012         check_added_monitors!(nodes[1], 1);
4013
4014         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4015         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4016         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4017         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4018         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4019         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4020         assert!(as_commitment_signed.update_fee.is_none());
4021         check_added_monitors!(nodes[0], 1);
4022
4023         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4024         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4025         // No commitment_signed so get_event_msg's assert(len == 1) passes
4026         check_added_monitors!(nodes[0], 1);
4027
4028         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4029         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4030         // No commitment_signed so get_event_msg's assert(len == 1) passes
4031         check_added_monitors!(nodes[1], 1);
4032
4033         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4034         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4035         check_added_monitors!(nodes[1], 1);
4036
4037         expect_pending_htlcs_forwardable!(nodes[1]);
4038
4039         let events_5 = nodes[1].node.get_and_clear_pending_events();
4040         assert_eq!(events_5.len(), 1);
4041         match events_5[0] {
4042                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt: _ } => {
4043                         assert_eq!(payment_hash_2, *payment_hash);
4044                         assert_eq!(*payment_secret, None);
4045                 },
4046                 _ => panic!("Unexpected event"),
4047         }
4048
4049         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4050         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4051         check_added_monitors!(nodes[0], 1);
4052
4053         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
4054 }
4055
4056 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4057         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4058         // to avoid our counterparty failing the channel.
4059         let chanmon_cfgs = create_chanmon_cfgs(2);
4060         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4061         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4062         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4063
4064         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4065         let logger = test_utils::TestLogger::new();
4066
4067         let our_payment_hash = if send_partial_mpp {
4068                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4069                 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();
4070                 let (_, our_payment_hash) = get_payment_preimage_hash!(&nodes[0]);
4071                 let payment_secret = PaymentSecret([0xdb; 32]);
4072                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4073                 // indicates there are more HTLCs coming.
4074                 nodes[0].node.send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200000, CHAN_CONFIRM_DEPTH).unwrap();
4075                 check_added_monitors!(nodes[0], 1);
4076                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4077                 assert_eq!(events.len(), 1);
4078                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4079                 // hop should *not* yet generate any PaymentReceived event(s).
4080                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false);
4081                 our_payment_hash
4082         } else {
4083                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4084         };
4085
4086         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4087         nodes[0].block_notifier.block_connected_checked(&header, 101, &[], &[]);
4088         nodes[1].block_notifier.block_connected_checked(&header, 101, &[], &[]);
4089         for i in 102..TEST_FINAL_CLTV + 100 + 1 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
4090                 header.prev_blockhash = header.block_hash();
4091                 nodes[0].block_notifier.block_connected_checked(&header, i, &[], &[]);
4092                 nodes[1].block_notifier.block_connected_checked(&header, i, &[], &[]);
4093         }
4094
4095         expect_pending_htlcs_forwardable!(nodes[1]);
4096
4097         check_added_monitors!(nodes[1], 1);
4098         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4099         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4100         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4101         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4102         assert!(htlc_timeout_updates.update_fee.is_none());
4103
4104         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4105         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4106         // 100_000 msat as u64, followed by a height of 123 as u32
4107         let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4108         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(123));
4109         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4110 }
4111
4112 #[test]
4113 fn test_htlc_timeout() {
4114         do_test_htlc_timeout(true);
4115         do_test_htlc_timeout(false);
4116 }
4117
4118 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4119         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4120         let chanmon_cfgs = create_chanmon_cfgs(3);
4121         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4122         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4123         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4124         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4125         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4126         let logger = test_utils::TestLogger::new();
4127
4128         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4129         let (_, first_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4130         {
4131                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4132                 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();
4133                 nodes[1].node.send_payment(&route, first_payment_hash, &None).unwrap();
4134         }
4135         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4136         check_added_monitors!(nodes[1], 1);
4137
4138         // Now attempt to route a second payment, which should be placed in the holding cell
4139         let (_, second_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4140         if forwarded_htlc {
4141                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4142                 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();
4143                 nodes[0].node.send_payment(&route, second_payment_hash, &None).unwrap();
4144                 check_added_monitors!(nodes[0], 1);
4145                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4146                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4147                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4148                 expect_pending_htlcs_forwardable!(nodes[1]);
4149                 check_added_monitors!(nodes[1], 0);
4150         } else {
4151                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4152                 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();
4153                 nodes[1].node.send_payment(&route, second_payment_hash, &None).unwrap();
4154                 check_added_monitors!(nodes[1], 0);
4155         }
4156
4157         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4158         nodes[1].block_notifier.block_connected_checked(&header, 101, &[], &[]);
4159         for i in 102..TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
4160                 header.prev_blockhash = header.block_hash();
4161                 nodes[1].block_notifier.block_connected_checked(&header, i, &[], &[]);
4162         }
4163
4164         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4165         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4166
4167         header.prev_blockhash = header.block_hash();
4168         nodes[1].block_notifier.block_connected_checked(&header, TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS, &[], &[]);
4169
4170         if forwarded_htlc {
4171                 expect_pending_htlcs_forwardable!(nodes[1]);
4172                 check_added_monitors!(nodes[1], 1);
4173                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4174                 assert_eq!(fail_commit.len(), 1);
4175                 match fail_commit[0] {
4176                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4177                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4178                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4179                         },
4180                         _ => unreachable!(),
4181                 }
4182                 expect_payment_failed!(nodes[0], second_payment_hash, false);
4183                 if let &MessageSendEvent::PaymentFailureNetworkUpdate { ref update } = &nodes[0].node.get_and_clear_pending_msg_events()[0] {
4184                         match update {
4185                                 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {},
4186                                 _ => panic!("Unexpected event"),
4187                         }
4188                 } else {
4189                         panic!("Unexpected event");
4190                 }
4191         } else {
4192                 expect_payment_failed!(nodes[1], second_payment_hash, true);
4193         }
4194 }
4195
4196 #[test]
4197 fn test_holding_cell_htlc_add_timeouts() {
4198         do_test_holding_cell_htlc_add_timeouts(false);
4199         do_test_holding_cell_htlc_add_timeouts(true);
4200 }
4201
4202 #[test]
4203 fn test_invalid_channel_announcement() {
4204         //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
4205         let secp_ctx = Secp256k1::new();
4206         let chanmon_cfgs = create_chanmon_cfgs(2);
4207         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4208         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4209         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4210
4211         let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
4212
4213         let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
4214         let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
4215         let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4216         let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4217
4218         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 } );
4219
4220         let as_bitcoin_key = as_chan.get_keys().inner.holder_channel_pubkeys.funding_pubkey;
4221         let bs_bitcoin_key = bs_chan.get_keys().inner.holder_channel_pubkeys.funding_pubkey;
4222
4223         let as_network_key = nodes[0].node.get_our_node_id();
4224         let bs_network_key = nodes[1].node.get_our_node_id();
4225
4226         let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
4227
4228         let mut chan_announcement;
4229
4230         macro_rules! dummy_unsigned_msg {
4231                 () => {
4232                         msgs::UnsignedChannelAnnouncement {
4233                                 features: ChannelFeatures::known(),
4234                                 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4235                                 short_channel_id: as_chan.get_short_channel_id().unwrap(),
4236                                 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
4237                                 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
4238                                 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
4239                                 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
4240                                 excess_data: Vec::new(),
4241                         };
4242                 }
4243         }
4244
4245         macro_rules! sign_msg {
4246                 ($unsigned_msg: expr) => {
4247                         let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
4248                         let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_keys().inner.funding_key);
4249                         let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_keys().inner.funding_key);
4250                         let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
4251                         let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
4252                         chan_announcement = msgs::ChannelAnnouncement {
4253                                 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
4254                                 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
4255                                 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
4256                                 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
4257                                 contents: $unsigned_msg
4258                         }
4259                 }
4260         }
4261
4262         let unsigned_msg = dummy_unsigned_msg!();
4263         sign_msg!(unsigned_msg);
4264         assert_eq!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap(), true);
4265         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 } );
4266
4267         // Configured with Network::Testnet
4268         let mut unsigned_msg = dummy_unsigned_msg!();
4269         unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.block_hash();
4270         sign_msg!(unsigned_msg);
4271         assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4272
4273         let mut unsigned_msg = dummy_unsigned_msg!();
4274         unsigned_msg.chain_hash = BlockHash::hash(&[1,2,3,4,5,6,7,8,9]);
4275         sign_msg!(unsigned_msg);
4276         assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4277 }
4278
4279 #[test]
4280 fn test_no_txn_manager_serialize_deserialize() {
4281         let chanmon_cfgs = create_chanmon_cfgs(2);
4282         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4283         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4284         let logger: test_utils::TestLogger;
4285         let fee_estimator: test_utils::TestFeeEstimator;
4286         let new_chan_monitor: test_utils::TestChannelMonitor;
4287         let keys_manager: test_utils::TestKeysInterface;
4288         let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4289         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4290
4291         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4292
4293         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4294
4295         let nodes_0_serialized = nodes[0].node.encode();
4296         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4297         nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
4298
4299         logger = test_utils::TestLogger::new();
4300         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4301         new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator);
4302         nodes[0].chan_monitor = &new_chan_monitor;
4303         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4304         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read).unwrap();
4305         assert!(chan_0_monitor_read.is_empty());
4306
4307         let mut nodes_0_read = &nodes_0_serialized[..];
4308         let config = UserConfig::default();
4309         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4310         let (_, nodes_0_deserialized_tmp) = {
4311                 let mut channel_monitors = HashMap::new();
4312                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4313                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4314                         default_config: config,
4315                         keys_manager: &keys_manager,
4316                         fee_estimator: &fee_estimator,
4317                         monitor: nodes[0].chan_monitor,
4318                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4319                         logger: &logger,
4320                         channel_monitors,
4321                 }).unwrap()
4322         };
4323         nodes_0_deserialized = nodes_0_deserialized_tmp;
4324         assert!(nodes_0_read.is_empty());
4325
4326         assert!(nodes[0].chan_monitor.add_monitor(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4327         nodes[0].node = &nodes_0_deserialized;
4328         nodes[0].block_notifier.register_listener(nodes[0].node);
4329         assert_eq!(nodes[0].node.list_channels().len(), 1);
4330         check_added_monitors!(nodes[0], 1);
4331
4332         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4333         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4334         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4335         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4336
4337         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4338         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4339         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4340         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4341
4342         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4343         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4344         for node in nodes.iter() {
4345                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4346                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4347                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4348         }
4349
4350         send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4351 }
4352
4353 #[test]
4354 fn test_manager_serialize_deserialize_events() {
4355         // This test makes sure the events field in ChannelManager survives de/serialization
4356         let chanmon_cfgs = create_chanmon_cfgs(2);
4357         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4358         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4359         let fee_estimator: test_utils::TestFeeEstimator;
4360         let logger: test_utils::TestLogger;
4361         let new_chan_monitor: test_utils::TestChannelMonitor;
4362         let keys_manager: test_utils::TestKeysInterface;
4363         let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4364         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4365
4366         // Start creating a channel, but stop right before broadcasting the event message FundingBroadcastSafe
4367         let channel_value = 100000;
4368         let push_msat = 10001;
4369         let a_flags = InitFeatures::known();
4370         let b_flags = InitFeatures::known();
4371         let node_a = nodes.pop().unwrap();
4372         let node_b = nodes.pop().unwrap();
4373         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4374         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()));
4375         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()));
4376
4377         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4378
4379         node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
4380         check_added_monitors!(node_a, 0);
4381
4382         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()));
4383         {
4384                 let mut added_monitors = node_b.chan_monitor.added_monitors.lock().unwrap();
4385                 assert_eq!(added_monitors.len(), 1);
4386                 assert_eq!(added_monitors[0].0, funding_output);
4387                 added_monitors.clear();
4388         }
4389
4390         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()));
4391         {
4392                 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
4393                 assert_eq!(added_monitors.len(), 1);
4394                 assert_eq!(added_monitors[0].0, funding_output);
4395                 added_monitors.clear();
4396         }
4397         // Normally, this is where node_a would check for a FundingBroadcastSafe event, but the test de/serializes first instead
4398
4399         nodes.push(node_a);
4400         nodes.push(node_b);
4401
4402         // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4403         let nodes_0_serialized = nodes[0].node.encode();
4404         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4405         nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
4406
4407         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4408         logger = test_utils::TestLogger::new();
4409         new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator);
4410         nodes[0].chan_monitor = &new_chan_monitor;
4411         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4412         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read).unwrap();
4413         assert!(chan_0_monitor_read.is_empty());
4414
4415         let mut nodes_0_read = &nodes_0_serialized[..];
4416         let config = UserConfig::default();
4417         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4418         let (_, nodes_0_deserialized_tmp) = {
4419                 let mut channel_monitors = HashMap::new();
4420                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4421                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4422                         default_config: config,
4423                         keys_manager: &keys_manager,
4424                         fee_estimator: &fee_estimator,
4425                         monitor: nodes[0].chan_monitor,
4426                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4427                         logger: &logger,
4428                         channel_monitors,
4429                 }).unwrap()
4430         };
4431         nodes_0_deserialized = nodes_0_deserialized_tmp;
4432         assert!(nodes_0_read.is_empty());
4433
4434         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4435
4436         assert!(nodes[0].chan_monitor.add_monitor(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4437         nodes[0].node = &nodes_0_deserialized;
4438
4439         // After deserializing, make sure the FundingBroadcastSafe event is still held by the channel manager
4440         let events_4 = nodes[0].node.get_and_clear_pending_events();
4441         assert_eq!(events_4.len(), 1);
4442         match events_4[0] {
4443                 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
4444                         assert_eq!(user_channel_id, 42);
4445                         assert_eq!(*funding_txo, funding_output);
4446                 },
4447                 _ => panic!("Unexpected event"),
4448         };
4449
4450         // Make sure the channel is functioning as though the de/serialization never happened
4451         nodes[0].block_notifier.register_listener(nodes[0].node);
4452         assert_eq!(nodes[0].node.list_channels().len(), 1);
4453         check_added_monitors!(nodes[0], 1);
4454
4455         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4456         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4457         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4458         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4459
4460         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4461         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4462         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4463         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4464
4465         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4466         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4467         for node in nodes.iter() {
4468                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4469                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4470                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4471         }
4472
4473         send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4474 }
4475
4476 #[test]
4477 fn test_simple_manager_serialize_deserialize() {
4478         let chanmon_cfgs = create_chanmon_cfgs(2);
4479         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4480         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4481         let logger: test_utils::TestLogger;
4482         let fee_estimator: test_utils::TestFeeEstimator;
4483         let new_chan_monitor: test_utils::TestChannelMonitor;
4484         let keys_manager: test_utils::TestKeysInterface;
4485         let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4486         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4487         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4488
4489         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4490         let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4491
4492         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4493
4494         let nodes_0_serialized = nodes[0].node.encode();
4495         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4496         nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
4497
4498         logger = test_utils::TestLogger::new();
4499         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4500         new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator);
4501         nodes[0].chan_monitor = &new_chan_monitor;
4502         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4503         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read).unwrap();
4504         assert!(chan_0_monitor_read.is_empty());
4505
4506         let mut nodes_0_read = &nodes_0_serialized[..];
4507         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4508         let (_, nodes_0_deserialized_tmp) = {
4509                 let mut channel_monitors = HashMap::new();
4510                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4511                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4512                         default_config: UserConfig::default(),
4513                         keys_manager: &keys_manager,
4514                         fee_estimator: &fee_estimator,
4515                         monitor: nodes[0].chan_monitor,
4516                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4517                         logger: &logger,
4518                         channel_monitors,
4519                 }).unwrap()
4520         };
4521         nodes_0_deserialized = nodes_0_deserialized_tmp;
4522         assert!(nodes_0_read.is_empty());
4523
4524         assert!(nodes[0].chan_monitor.add_monitor(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4525         nodes[0].node = &nodes_0_deserialized;
4526         check_added_monitors!(nodes[0], 1);
4527
4528         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4529
4530         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4531         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage, 1_000_000);
4532 }
4533
4534 #[test]
4535 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4536         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4537         let chanmon_cfgs = create_chanmon_cfgs(4);
4538         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4539         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4540         let logger: test_utils::TestLogger;
4541         let fee_estimator: test_utils::TestFeeEstimator;
4542         let new_chan_monitor: test_utils::TestChannelMonitor;
4543         let keys_manager: test_utils::TestKeysInterface;
4544         let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4545         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4546         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4547         create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known());
4548         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4549
4550         let mut node_0_stale_monitors_serialized = Vec::new();
4551         for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
4552                 let mut writer = test_utils::TestVecWriter(Vec::new());
4553                 monitor.1.write_for_disk(&mut writer).unwrap();
4554                 node_0_stale_monitors_serialized.push(writer.0);
4555         }
4556
4557         let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4558
4559         // Serialize the ChannelManager here, but the monitor we keep up-to-date
4560         let nodes_0_serialized = nodes[0].node.encode();
4561
4562         route_payment(&nodes[0], &[&nodes[3]], 1000000);
4563         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4564         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4565         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4566
4567         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4568         // nodes[3])
4569         let mut node_0_monitors_serialized = Vec::new();
4570         for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
4571                 let mut writer = test_utils::TestVecWriter(Vec::new());
4572                 monitor.1.write_for_disk(&mut writer).unwrap();
4573                 node_0_monitors_serialized.push(writer.0);
4574         }
4575
4576         logger = test_utils::TestLogger::new();
4577         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4578         new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator);
4579         nodes[0].chan_monitor = &new_chan_monitor;
4580
4581         let mut node_0_stale_monitors = Vec::new();
4582         for serialized in node_0_stale_monitors_serialized.iter() {
4583                 let mut read = &serialized[..];
4584                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read).unwrap();
4585                 assert!(read.is_empty());
4586                 node_0_stale_monitors.push(monitor);
4587         }
4588
4589         let mut node_0_monitors = Vec::new();
4590         for serialized in node_0_monitors_serialized.iter() {
4591                 let mut read = &serialized[..];
4592                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read).unwrap();
4593                 assert!(read.is_empty());
4594                 node_0_monitors.push(monitor);
4595         }
4596
4597         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4598
4599         let mut nodes_0_read = &nodes_0_serialized[..];
4600         if let Err(msgs::DecodeError::InvalidValue) =
4601                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4602                 default_config: UserConfig::default(),
4603                 keys_manager: &keys_manager,
4604                 fee_estimator: &fee_estimator,
4605                 monitor: nodes[0].chan_monitor,
4606                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4607                 logger: &logger,
4608                 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4609         }) { } else {
4610                 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4611         };
4612
4613         let mut nodes_0_read = &nodes_0_serialized[..];
4614         let (_, nodes_0_deserialized_tmp) =
4615                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4616                 default_config: UserConfig::default(),
4617                 keys_manager: &keys_manager,
4618                 fee_estimator: &fee_estimator,
4619                 monitor: nodes[0].chan_monitor,
4620                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4621                 logger: &logger,
4622                 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4623         }).unwrap();
4624         nodes_0_deserialized = nodes_0_deserialized_tmp;
4625         assert!(nodes_0_read.is_empty());
4626
4627         { // Channel close should result in a commitment tx and an HTLC tx
4628                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4629                 assert_eq!(txn.len(), 2);
4630                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4631                 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
4632         }
4633
4634         for monitor in node_0_monitors.drain(..) {
4635                 assert!(nodes[0].chan_monitor.add_monitor(monitor.get_funding_txo().0, monitor).is_ok());
4636                 check_added_monitors!(nodes[0], 1);
4637         }
4638         nodes[0].node = &nodes_0_deserialized;
4639
4640         // nodes[1] and nodes[2] have no lost state with nodes[0]...
4641         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4642         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4643         //... and we can even still claim the payment!
4644         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage, 1_000_000);
4645
4646         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4647         let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4648         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4649         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4650         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4651         assert_eq!(msg_events.len(), 1);
4652         if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4653                 match action {
4654                         &ErrorAction::SendErrorMessage { ref msg } => {
4655                                 assert_eq!(msg.channel_id, channel_id);
4656                         },
4657                         _ => panic!("Unexpected event!"),
4658                 }
4659         }
4660 }
4661
4662 macro_rules! check_spendable_outputs {
4663         ($node: expr, $der_idx: expr, $keysinterface: expr, $chan_value: expr) => {
4664                 {
4665                         let events = $node.chan_monitor.simple_monitor.get_and_clear_pending_events();
4666                         let mut txn = Vec::new();
4667                         for event in events {
4668                                 match event {
4669                                         Event::SpendableOutputs { ref outputs } => {
4670                                                 for outp in outputs {
4671                                                         match *outp {
4672                                                                 SpendableOutputDescriptor::StaticOutputCounterpartyPayment { ref outpoint, ref output, ref key_derivation_params } => {
4673                                                                         let input = TxIn {
4674                                                                                 previous_output: outpoint.into_bitcoin_outpoint(),
4675                                                                                 script_sig: Script::new(),
4676                                                                                 sequence: 0,
4677                                                                                 witness: Vec::new(),
4678                                                                         };
4679                                                                         let outp = TxOut {
4680                                                                                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4681                                                                                 value: output.value,
4682                                                                         };
4683                                                                         let mut spend_tx = Transaction {
4684                                                                                 version: 2,
4685                                                                                 lock_time: 0,
4686                                                                                 input: vec![input],
4687                                                                                 output: vec![outp],
4688                                                                         };
4689                                                                         let secp_ctx = Secp256k1::new();
4690                                                                         let keys = $keysinterface.derive_channel_keys($chan_value, key_derivation_params.0, key_derivation_params.1);
4691                                                                         let remotepubkey = keys.pubkeys().payment_point;
4692                                                                         let witness_script = Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: remotepubkey}, Network::Testnet).script_pubkey();
4693                                                                         let sighash = Message::from_slice(&bip143::SigHashCache::new(&spend_tx).signature_hash(0, &witness_script, output.value, SigHashType::All)[..]).unwrap();
4694                                                                         let remotesig = secp_ctx.sign(&sighash, &keys.inner.payment_key);
4695                                                                         spend_tx.input[0].witness.push(remotesig.serialize_der().to_vec());
4696                                                                         spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4697                                                                         spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
4698                                                                         txn.push(spend_tx);
4699                                                                 },
4700                                                                 SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref per_commitment_point, ref to_self_delay, ref output, ref key_derivation_params, ref revocation_pubkey } => {
4701                                                                         let input = TxIn {
4702                                                                                 previous_output: outpoint.into_bitcoin_outpoint(),
4703                                                                                 script_sig: Script::new(),
4704                                                                                 sequence: *to_self_delay as u32,
4705                                                                                 witness: Vec::new(),
4706                                                                         };
4707                                                                         let outp = TxOut {
4708                                                                                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4709                                                                                 value: output.value,
4710                                                                         };
4711                                                                         let mut spend_tx = Transaction {
4712                                                                                 version: 2,
4713                                                                                 lock_time: 0,
4714                                                                                 input: vec![input],
4715                                                                                 output: vec![outp],
4716                                                                         };
4717                                                                         let secp_ctx = Secp256k1::new();
4718                                                                         let keys = $keysinterface.derive_channel_keys($chan_value, key_derivation_params.0, key_derivation_params.1);
4719                                                                         if let Ok(delayed_payment_key) = chan_utils::derive_private_key(&secp_ctx, &per_commitment_point, &keys.inner.delayed_payment_base_key) {
4720
4721                                                                                 let delayed_payment_pubkey = PublicKey::from_secret_key(&secp_ctx, &delayed_payment_key);
4722                                                                                 let witness_script = chan_utils::get_revokeable_redeemscript(revocation_pubkey, *to_self_delay, &delayed_payment_pubkey);
4723                                                                                 let sighash = Message::from_slice(&bip143::SigHashCache::new(&spend_tx).signature_hash(0, &witness_script, output.value, SigHashType::All)[..]).unwrap();
4724                                                                                 let local_delayedsig = secp_ctx.sign(&sighash, &delayed_payment_key);
4725                                                                                 spend_tx.input[0].witness.push(local_delayedsig.serialize_der().to_vec());
4726                                                                                 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4727                                                                                 spend_tx.input[0].witness.push(vec!()); //MINIMALIF
4728                                                                                 spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
4729                                                                         } else { panic!() }
4730                                                                         txn.push(spend_tx);
4731                                                                 },
4732                                                                 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
4733                                                                         let secp_ctx = Secp256k1::new();
4734                                                                         let input = TxIn {
4735                                                                                 previous_output: outpoint.into_bitcoin_outpoint(),
4736                                                                                 script_sig: Script::new(),
4737                                                                                 sequence: 0,
4738                                                                                 witness: Vec::new(),
4739                                                                         };
4740                                                                         let outp = TxOut {
4741                                                                                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4742                                                                                 value: output.value,
4743                                                                         };
4744                                                                         let mut spend_tx = Transaction {
4745                                                                                 version: 2,
4746                                                                                 lock_time: 0,
4747                                                                                 input: vec![input],
4748                                                                                 output: vec![outp.clone()],
4749                                                                         };
4750                                                                         let secret = {
4751                                                                                 match ExtendedPrivKey::new_master(Network::Testnet, &$node.node_seed) {
4752                                                                                         Ok(master_key) => {
4753                                                                                                 match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx).expect("key space exhausted")) {
4754                                                                                                         Ok(key) => key,
4755                                                                                                         Err(_) => panic!("Your RNG is busted"),
4756                                                                                                 }
4757                                                                                         }
4758                                                                                         Err(_) => panic!("Your rng is busted"),
4759                                                                                 }
4760                                                                         };
4761                                                                         let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
4762                                                                         let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
4763                                                                         let sighash = Message::from_slice(&bip143::SigHashCache::new(&spend_tx).signature_hash(0, &witness_script, output.value, SigHashType::All)[..]).unwrap();
4764                                                                         let sig = secp_ctx.sign(&sighash, &secret.private_key.key);
4765                                                                         spend_tx.input[0].witness.push(sig.serialize_der().to_vec());
4766                                                                         spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4767                                                                         spend_tx.input[0].witness.push(pubkey.key.serialize().to_vec());
4768                                                                         txn.push(spend_tx);
4769                                                                 },
4770                                                         }
4771                                                 }
4772                                         },
4773                                         _ => panic!("Unexpected event"),
4774                                 };
4775                         }
4776                         txn
4777                 }
4778         }
4779 }
4780
4781 #[test]
4782 fn test_claim_sizeable_push_msat() {
4783         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4784         let chanmon_cfgs = create_chanmon_cfgs(2);
4785         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4786         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4787         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4788
4789         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4790         nodes[1].node.force_close_channel(&chan.2);
4791         check_closed_broadcast!(nodes[1], false);
4792         check_added_monitors!(nodes[1], 1);
4793         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4794         assert_eq!(node_txn.len(), 1);
4795         check_spends!(node_txn[0], chan.3);
4796         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
4797
4798         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4799         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4800         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4801
4802         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4803         assert_eq!(spend_txn.len(), 1);
4804         check_spends!(spend_txn[0], node_txn[0]);
4805 }
4806
4807 #[test]
4808 fn test_claim_on_remote_sizeable_push_msat() {
4809         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4810         // to_remote output is encumbered by a P2WPKH
4811         let chanmon_cfgs = create_chanmon_cfgs(2);
4812         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4813         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4814         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4815
4816         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4817         nodes[0].node.force_close_channel(&chan.2);
4818         check_closed_broadcast!(nodes[0], false);
4819         check_added_monitors!(nodes[0], 1);
4820
4821         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4822         assert_eq!(node_txn.len(), 1);
4823         check_spends!(node_txn[0], chan.3);
4824         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
4825
4826         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4827         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4828         check_closed_broadcast!(nodes[1], false);
4829         check_added_monitors!(nodes[1], 1);
4830         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4831
4832         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4833         assert_eq!(spend_txn.len(), 2);
4834         assert_eq!(spend_txn[0], spend_txn[1]);
4835         check_spends!(spend_txn[0], node_txn[0]);
4836 }
4837
4838 #[test]
4839 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4840         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4841         // to_remote output is encumbered by a P2WPKH
4842
4843         let chanmon_cfgs = create_chanmon_cfgs(2);
4844         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4845         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4846         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4847
4848         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4849         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4850         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4851         assert_eq!(revoked_local_txn[0].input.len(), 1);
4852         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4853
4854         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4855         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4856         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
4857         check_closed_broadcast!(nodes[1], false);
4858         check_added_monitors!(nodes[1], 1);
4859
4860         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4861         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4862         nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4863         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4864
4865         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4866         assert_eq!(spend_txn.len(), 3);
4867         assert_eq!(spend_txn[0], spend_txn[1]); // to_remote output on revoked remote commitment_tx
4868         check_spends!(spend_txn[0], revoked_local_txn[0]);
4869         check_spends!(spend_txn[2], node_txn[0]);
4870 }
4871
4872 #[test]
4873 fn test_static_spendable_outputs_preimage_tx() {
4874         let chanmon_cfgs = create_chanmon_cfgs(2);
4875         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4876         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4877         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4878
4879         // Create some initial channels
4880         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4881
4882         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4883
4884         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4885         assert_eq!(commitment_tx[0].input.len(), 1);
4886         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4887
4888         // Settle A's commitment tx on B's chain
4889         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4890         assert!(nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000));
4891         check_added_monitors!(nodes[1], 1);
4892         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
4893         check_added_monitors!(nodes[1], 1);
4894         let events = nodes[1].node.get_and_clear_pending_msg_events();
4895         match events[0] {
4896                 MessageSendEvent::UpdateHTLCs { .. } => {},
4897                 _ => panic!("Unexpected event"),
4898         }
4899         match events[1] {
4900                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4901                 _ => panic!("Unexepected event"),
4902         }
4903
4904         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4905         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4906         assert_eq!(node_txn.len(), 3);
4907         check_spends!(node_txn[0], commitment_tx[0]);
4908         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4909         check_spends!(node_txn[1], chan_1.3);
4910         check_spends!(node_txn[2], node_txn[1]);
4911
4912         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4913         nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4914         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4915
4916         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4917         assert_eq!(spend_txn.len(), 1);
4918         check_spends!(spend_txn[0], node_txn[0]);
4919 }
4920
4921 #[test]
4922 fn test_static_spendable_outputs_timeout_tx() {
4923         let chanmon_cfgs = create_chanmon_cfgs(2);
4924         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4925         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4926         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4927
4928         // Create some initial channels
4929         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4930
4931         // Rebalance the network a bit by relaying one payment through all the channels ...
4932         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
4933
4934         let (_, our_payment_hash) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4935
4936         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4937         assert_eq!(commitment_tx[0].input.len(), 1);
4938         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4939
4940         // Settle A's commitment tx on B' chain
4941         let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
4942         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 0);
4943         check_added_monitors!(nodes[1], 1);
4944         let events = nodes[1].node.get_and_clear_pending_msg_events();
4945         match events[0] {
4946                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4947                 _ => panic!("Unexpected event"),
4948         }
4949
4950         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4951         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4952         assert_eq!(node_txn.len(), 3); // ChannelManager : 2 (local commitent tx + HTLC-timeout), ChannelMonitor: timeout tx
4953         check_spends!(node_txn[0],  commitment_tx[0].clone());
4954         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4955         check_spends!(node_txn[1], chan_1.3.clone());
4956         check_spends!(node_txn[2], node_txn[1]);
4957
4958         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4959         nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4960         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4961         expect_payment_failed!(nodes[1], our_payment_hash, true);
4962
4963         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4964         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote (*2), timeout_tx.output (*1)
4965         check_spends!(spend_txn[2], node_txn[0].clone());
4966 }
4967
4968 #[test]
4969 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4970         let chanmon_cfgs = create_chanmon_cfgs(2);
4971         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4972         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4973         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4974
4975         // Create some initial channels
4976         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4977
4978         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4979         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4980         assert_eq!(revoked_local_txn[0].input.len(), 1);
4981         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4982
4983         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4984
4985         let  header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4986         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
4987         check_closed_broadcast!(nodes[1], false);
4988         check_added_monitors!(nodes[1], 1);
4989
4990         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4991         assert_eq!(node_txn.len(), 2);
4992         assert_eq!(node_txn[0].input.len(), 2);
4993         check_spends!(node_txn[0], revoked_local_txn[0]);
4994
4995         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4996         nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4997         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4998
4999         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5000         assert_eq!(spend_txn.len(), 1);
5001         check_spends!(spend_txn[0], node_txn[0]);
5002 }
5003
5004 #[test]
5005 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
5006         let chanmon_cfgs = create_chanmon_cfgs(2);
5007         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5008         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5009         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5010
5011         // Create some initial channels
5012         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5013
5014         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5015         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5016         assert_eq!(revoked_local_txn[0].input.len(), 1);
5017         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5018
5019         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
5020
5021         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5022         // A will generate HTLC-Timeout from revoked commitment tx
5023         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5024         check_closed_broadcast!(nodes[0], false);
5025         check_added_monitors!(nodes[0], 1);
5026
5027         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5028         assert_eq!(revoked_htlc_txn.len(), 2);
5029         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5030         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5031         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5032         check_spends!(revoked_htlc_txn[1], chan_1.3);
5033
5034         // B will generate justice tx from A's revoked commitment/HTLC tx
5035         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 0);
5036         check_closed_broadcast!(nodes[1], false);
5037         check_added_monitors!(nodes[1], 1);
5038
5039         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5040         assert_eq!(node_txn.len(), 4); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-timeout, adjusted justice tx, ChannelManager: local commitment tx
5041         assert_eq!(node_txn[0].input.len(), 2);
5042         check_spends!(node_txn[0], revoked_local_txn[0]);
5043         check_spends!(node_txn[1], chan_1.3);
5044         assert_eq!(node_txn[2].input.len(), 1);
5045         check_spends!(node_txn[2], revoked_htlc_txn[0]);
5046         assert_eq!(node_txn[3].input.len(), 1);
5047         check_spends!(node_txn[3], revoked_local_txn[0]);
5048
5049         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5050         nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone(), node_txn[2].clone()] }, 1);
5051         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5052
5053         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
5054         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5055         assert_eq!(spend_txn.len(), 2);
5056         check_spends!(spend_txn[0], node_txn[0]);
5057         check_spends!(spend_txn[1], node_txn[2]);
5058 }
5059
5060 #[test]
5061 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
5062         let chanmon_cfgs = create_chanmon_cfgs(2);
5063         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5064         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5065         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5066
5067         // Create some initial channels
5068         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5069
5070         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5071         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5072         assert_eq!(revoked_local_txn[0].input.len(), 1);
5073         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5074
5075         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
5076
5077         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5078         // B will generate HTLC-Success from revoked commitment tx
5079         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5080         check_closed_broadcast!(nodes[1], false);
5081         check_added_monitors!(nodes[1], 1);
5082         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5083
5084         assert_eq!(revoked_htlc_txn.len(), 2);
5085         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5086         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5087         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5088
5089         // A will generate justice tx from B's revoked commitment/HTLC tx
5090         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
5091         check_closed_broadcast!(nodes[0], false);
5092         check_added_monitors!(nodes[0], 1);
5093
5094         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5095         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5096         assert_eq!(node_txn[2].input.len(), 1);
5097         check_spends!(node_txn[2], revoked_htlc_txn[0]);
5098
5099         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5100         nodes[0].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone(), node_txn[2].clone()] }, 1);
5101         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5102
5103         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5104         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5105         assert_eq!(spend_txn.len(), 5); // Duplicated SpendableOutput due to block rescan after revoked htlc output tracking
5106         assert_eq!(spend_txn[0], spend_txn[1]);
5107         assert_eq!(spend_txn[0], spend_txn[2]);
5108         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5109         check_spends!(spend_txn[3], node_txn[0]); // spending justice tx output from revoked local tx htlc received output
5110         check_spends!(spend_txn[4], node_txn[2]); // spending justice tx output on htlc success tx
5111 }
5112
5113 #[test]
5114 fn test_onchain_to_onchain_claim() {
5115         // Test that in case of channel closure, we detect the state of output thanks to
5116         // ChainWatchInterface and claim HTLC on downstream peer's remote commitment tx.
5117         // First, have C claim an HTLC against its own latest commitment transaction.
5118         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5119         // channel.
5120         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5121         // gets broadcast.
5122
5123         let chanmon_cfgs = create_chanmon_cfgs(3);
5124         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5125         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5126         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5127
5128         // Create some initial channels
5129         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5130         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5131
5132         // Rebalance the network a bit by relaying one payment through all the channels ...
5133         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5134         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5135
5136         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5137         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5138         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5139         check_spends!(commitment_tx[0], chan_2.3);
5140         nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000);
5141         check_added_monitors!(nodes[2], 1);
5142         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5143         assert!(updates.update_add_htlcs.is_empty());
5144         assert!(updates.update_fail_htlcs.is_empty());
5145         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5146         assert!(updates.update_fail_malformed_htlcs.is_empty());
5147
5148         nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
5149         check_closed_broadcast!(nodes[2], false);
5150         check_added_monitors!(nodes[2], 1);
5151
5152         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5153         assert_eq!(c_txn.len(), 3);
5154         assert_eq!(c_txn[0], c_txn[2]);
5155         assert_eq!(commitment_tx[0], c_txn[1]);
5156         check_spends!(c_txn[1], chan_2.3);
5157         check_spends!(c_txn[2], c_txn[1]);
5158         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5159         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5160         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5161         assert_eq!(c_txn[0].lock_time, 0); // Success tx
5162
5163         // 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
5164         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
5165         {
5166                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5167                 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-timeout tx
5168                 assert_eq!(b_txn.len(), 3);
5169                 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
5170                 check_spends!(b_txn[2], b_txn[1]); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
5171                 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5172                 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5173                 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5174                 check_spends!(b_txn[0], c_txn[1]); // timeout tx on C remote commitment tx, issued by ChannelMonitor, * 2 due to block rescan
5175                 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5176                 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5177                 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5178                 b_txn.clear();
5179         }
5180         check_added_monitors!(nodes[1], 1);
5181         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5182         check_added_monitors!(nodes[1], 1);
5183         match msg_events[0] {
5184                 MessageSendEvent::BroadcastChannelUpdate {  .. } => {},
5185                 _ => panic!("Unexpected event"),
5186         }
5187         match msg_events[1] {
5188                 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, .. } } => {
5189                         assert!(update_add_htlcs.is_empty());
5190                         assert!(update_fail_htlcs.is_empty());
5191                         assert_eq!(update_fulfill_htlcs.len(), 1);
5192                         assert!(update_fail_malformed_htlcs.is_empty());
5193                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5194                 },
5195                 _ => panic!("Unexpected event"),
5196         };
5197         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5198         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5199         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
5200         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5201         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5202         assert_eq!(b_txn.len(), 3);
5203         check_spends!(b_txn[1], chan_1.3);
5204         check_spends!(b_txn[2], b_txn[1]);
5205         check_spends!(b_txn[0], commitment_tx[0]);
5206         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5207         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5208         assert_eq!(b_txn[0].lock_time, 0); // Success tx
5209
5210         check_closed_broadcast!(nodes[1], false);
5211         check_added_monitors!(nodes[1], 1);
5212 }
5213
5214 #[test]
5215 fn test_duplicate_payment_hash_one_failure_one_success() {
5216         // Topology : A --> B --> C
5217         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5218         let chanmon_cfgs = create_chanmon_cfgs(3);
5219         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5220         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5221         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5222
5223         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5224         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5225
5226         let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5227         *nodes[0].network_payment_count.borrow_mut() -= 1;
5228         assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
5229
5230         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5231         assert_eq!(commitment_txn[0].input.len(), 1);
5232         check_spends!(commitment_txn[0], chan_2.3);
5233
5234         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5235         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
5236         check_closed_broadcast!(nodes[1], false);
5237         check_added_monitors!(nodes[1], 1);
5238
5239         let htlc_timeout_tx;
5240         { // Extract one of the two HTLC-Timeout transaction
5241                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5242                 // ChannelMonitor: timeout tx * 2, ChannelManager: local commitment tx + HTLC-timeout * 2
5243                 assert_eq!(node_txn.len(), 5);
5244                 check_spends!(node_txn[0], commitment_txn[0]);
5245                 assert_eq!(node_txn[0].input.len(), 1);
5246                 check_spends!(node_txn[1], commitment_txn[0]);
5247                 assert_eq!(node_txn[1].input.len(), 1);
5248                 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
5249                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5250                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5251                 check_spends!(node_txn[2], chan_2.3);
5252                 check_spends!(node_txn[3], node_txn[2]);
5253                 check_spends!(node_txn[4], node_txn[2]);
5254                 htlc_timeout_tx = node_txn[1].clone();
5255         }
5256
5257         nodes[2].node.claim_funds(our_payment_preimage, &None, 900_000);
5258         nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
5259         check_added_monitors!(nodes[2], 3);
5260         let events = nodes[2].node.get_and_clear_pending_msg_events();
5261         match events[0] {
5262                 MessageSendEvent::UpdateHTLCs { .. } => {},
5263                 _ => panic!("Unexpected event"),
5264         }
5265         match events[1] {
5266                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5267                 _ => panic!("Unexepected event"),
5268         }
5269         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5270         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)
5271         check_spends!(htlc_success_txn[2], chan_2.3);
5272         check_spends!(htlc_success_txn[3], htlc_success_txn[2]);
5273         check_spends!(htlc_success_txn[4], htlc_success_txn[2]);
5274         assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
5275         assert_eq!(htlc_success_txn[0].input.len(), 1);
5276         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5277         assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
5278         assert_eq!(htlc_success_txn[1].input.len(), 1);
5279         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5280         assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
5281         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5282         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5283
5284         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![htlc_timeout_tx] }, 200);
5285         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 200, true, header.block_hash());
5286         expect_pending_htlcs_forwardable!(nodes[1]);
5287         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5288         assert!(htlc_updates.update_add_htlcs.is_empty());
5289         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5290         assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
5291         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5292         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5293         check_added_monitors!(nodes[1], 1);
5294
5295         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5296         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5297         {
5298                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5299                 let events = nodes[0].node.get_and_clear_pending_msg_events();
5300                 assert_eq!(events.len(), 1);
5301                 match events[0] {
5302                         MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. }  } => {
5303                         },
5304                         _ => { panic!("Unexpected event"); }
5305                 }
5306         }
5307         expect_payment_failed!(nodes[0], duplicate_payment_hash, false);
5308
5309         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5310         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
5311         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5312         assert!(updates.update_add_htlcs.is_empty());
5313         assert!(updates.update_fail_htlcs.is_empty());
5314         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5315         assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
5316         assert!(updates.update_fail_malformed_htlcs.is_empty());
5317         check_added_monitors!(nodes[1], 1);
5318
5319         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5320         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5321
5322         let events = nodes[0].node.get_and_clear_pending_events();
5323         match events[0] {
5324                 Event::PaymentSent { ref payment_preimage } => {
5325                         assert_eq!(*payment_preimage, our_payment_preimage);
5326                 }
5327                 _ => panic!("Unexpected event"),
5328         }
5329 }
5330
5331 #[test]
5332 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5333         let chanmon_cfgs = create_chanmon_cfgs(2);
5334         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5335         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5336         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5337
5338         // Create some initial channels
5339         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5340
5341         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5342         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5343         assert_eq!(local_txn[0].input.len(), 1);
5344         check_spends!(local_txn[0], chan_1.3);
5345
5346         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5347         nodes[1].node.claim_funds(payment_preimage, &None, 9_000_000);
5348         check_added_monitors!(nodes[1], 1);
5349         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5350         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![local_txn[0].clone()] }, 1);
5351         check_added_monitors!(nodes[1], 1);
5352         let events = nodes[1].node.get_and_clear_pending_msg_events();
5353         match events[0] {
5354                 MessageSendEvent::UpdateHTLCs { .. } => {},
5355                 _ => panic!("Unexpected event"),
5356         }
5357         match events[1] {
5358                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5359                 _ => panic!("Unexepected event"),
5360         }
5361         let node_txn = {
5362                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5363                 assert_eq!(node_txn[0].input.len(), 1);
5364                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5365                 check_spends!(node_txn[0], local_txn[0]);
5366                 vec![node_txn[0].clone(), node_txn[2].clone()]
5367         };
5368
5369         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5370         nodes[1].block_notifier.block_connected(&Block { header: header_201, txdata: node_txn.clone() }, 201);
5371         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5372
5373         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5374         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5375         assert_eq!(spend_txn.len(), 2);
5376         check_spends!(spend_txn[0], node_txn[0]);
5377         check_spends!(spend_txn[1], node_txn[1]);
5378 }
5379
5380 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5381         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5382         // unrevoked commitment transaction.
5383         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5384         // a remote RAA before they could be failed backwards (and combinations thereof).
5385         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5386         // use the same payment hashes.
5387         // Thus, we use a six-node network:
5388         //
5389         // A \         / E
5390         //    - C - D -
5391         // B /         \ F
5392         // And test where C fails back to A/B when D announces its latest commitment transaction
5393         let chanmon_cfgs = create_chanmon_cfgs(6);
5394         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5395         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
5396         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5397         let logger = test_utils::TestLogger::new();
5398
5399         create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5400         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5401         let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5402         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5403         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5404
5405         // Rebalance and check output sanity...
5406         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000, 500_000);
5407         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000, 500_000);
5408         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5409
5410         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5411         // 0th HTLC:
5412         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
5413         // 1st HTLC:
5414         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
5415         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
5416         let our_node_id = &nodes[1].node.get_our_node_id();
5417         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();
5418         // 2nd HTLC:
5419         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
5420         // 3rd HTLC:
5421         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
5422         // 4th HTLC:
5423         let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5424         // 5th HTLC:
5425         let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5426         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();
5427         // 6th HTLC:
5428         send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
5429         // 7th HTLC:
5430         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
5431
5432         // 8th HTLC:
5433         let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5434         // 9th HTLC:
5435         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();
5436         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
5437
5438         // 10th HTLC:
5439         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
5440         // 11th HTLC:
5441         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();
5442         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
5443
5444         // Double-check that six of the new HTLC were added
5445         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5446         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5447         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5448         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5449
5450         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5451         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5452         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1, &None));
5453         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3, &None));
5454         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5, &None));
5455         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6, &None));
5456         check_added_monitors!(nodes[4], 0);
5457         expect_pending_htlcs_forwardable!(nodes[4]);
5458         check_added_monitors!(nodes[4], 1);
5459
5460         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5461         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5462         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5463         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5464         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5465         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5466
5467         // Fail 3rd below-dust and 7th above-dust HTLCs
5468         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2, &None));
5469         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4, &None));
5470         check_added_monitors!(nodes[5], 0);
5471         expect_pending_htlcs_forwardable!(nodes[5]);
5472         check_added_monitors!(nodes[5], 1);
5473
5474         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5475         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5476         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5477         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5478
5479         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5480
5481         expect_pending_htlcs_forwardable!(nodes[3]);
5482         check_added_monitors!(nodes[3], 1);
5483         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5484         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5485         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5486         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5487         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5488         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5489         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5490         if deliver_last_raa {
5491                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5492         } else {
5493                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5494         }
5495
5496         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5497         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5498         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5499         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5500         //
5501         // We now broadcast the latest commitment transaction, which *should* result in failures for
5502         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5503         // the non-broadcast above-dust HTLCs.
5504         //
5505         // Alternatively, we may broadcast the previous commitment transaction, which should only
5506         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5507         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5508
5509         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5510         if announce_latest {
5511                 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![ds_last_commitment_tx[0].clone()]}, 1);
5512         } else {
5513                 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![ds_prev_commitment_tx[0].clone()]}, 1);
5514         }
5515         connect_blocks(&nodes[2].block_notifier, ANTI_REORG_DELAY - 1, 1, true,  header.block_hash());
5516         check_closed_broadcast!(nodes[2], false);
5517         expect_pending_htlcs_forwardable!(nodes[2]);
5518         check_added_monitors!(nodes[2], 3);
5519
5520         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5521         assert_eq!(cs_msgs.len(), 2);
5522         let mut a_done = false;
5523         for msg in cs_msgs {
5524                 match msg {
5525                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5526                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5527                                 // should be failed-backwards here.
5528                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5529                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5530                                         for htlc in &updates.update_fail_htlcs {
5531                                                 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 });
5532                                         }
5533                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5534                                         assert!(!a_done);
5535                                         a_done = true;
5536                                         &nodes[0]
5537                                 } else {
5538                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5539                                         for htlc in &updates.update_fail_htlcs {
5540                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5541                                         }
5542                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5543                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5544                                         &nodes[1]
5545                                 };
5546                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5547                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5548                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5549                                 if announce_latest {
5550                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5551                                         if *node_id == nodes[0].node.get_our_node_id() {
5552                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5553                                         }
5554                                 }
5555                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5556                         },
5557                         _ => panic!("Unexpected event"),
5558                 }
5559         }
5560
5561         let as_events = nodes[0].node.get_and_clear_pending_events();
5562         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5563         let mut as_failds = HashSet::new();
5564         for event in as_events.iter() {
5565                 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5566                         assert!(as_failds.insert(*payment_hash));
5567                         if *payment_hash != payment_hash_2 {
5568                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5569                         } else {
5570                                 assert!(!rejected_by_dest);
5571                         }
5572                 } else { panic!("Unexpected event"); }
5573         }
5574         assert!(as_failds.contains(&payment_hash_1));
5575         assert!(as_failds.contains(&payment_hash_2));
5576         if announce_latest {
5577                 assert!(as_failds.contains(&payment_hash_3));
5578                 assert!(as_failds.contains(&payment_hash_5));
5579         }
5580         assert!(as_failds.contains(&payment_hash_6));
5581
5582         let bs_events = nodes[1].node.get_and_clear_pending_events();
5583         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5584         let mut bs_failds = HashSet::new();
5585         for event in bs_events.iter() {
5586                 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5587                         assert!(bs_failds.insert(*payment_hash));
5588                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5589                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5590                         } else {
5591                                 assert!(!rejected_by_dest);
5592                         }
5593                 } else { panic!("Unexpected event"); }
5594         }
5595         assert!(bs_failds.contains(&payment_hash_1));
5596         assert!(bs_failds.contains(&payment_hash_2));
5597         if announce_latest {
5598                 assert!(bs_failds.contains(&payment_hash_4));
5599         }
5600         assert!(bs_failds.contains(&payment_hash_5));
5601
5602         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5603         // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
5604         // to unknown-preimage-etc, B should have gotten 2. Thus, in the
5605         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
5606         // PaymentFailureNetworkUpdates.
5607         let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
5608         assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5609         let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5610         assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5611         for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
5612                 match event {
5613                         &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
5614                         _ => panic!("Unexpected event"),
5615                 }
5616         }
5617 }
5618
5619 #[test]
5620 fn test_fail_backwards_latest_remote_announce_a() {
5621         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5622 }
5623
5624 #[test]
5625 fn test_fail_backwards_latest_remote_announce_b() {
5626         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5627 }
5628
5629 #[test]
5630 fn test_fail_backwards_previous_remote_announce() {
5631         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5632         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5633         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5634 }
5635
5636 #[test]
5637 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5638         let chanmon_cfgs = create_chanmon_cfgs(2);
5639         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5640         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5641         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5642
5643         // Create some initial channels
5644         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5645
5646         let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5647         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5648         assert_eq!(local_txn[0].input.len(), 1);
5649         check_spends!(local_txn[0], chan_1.3);
5650
5651         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5652         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5653         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![local_txn[0].clone()] }, 200);
5654         check_closed_broadcast!(nodes[0], false);
5655         check_added_monitors!(nodes[0], 1);
5656
5657         let htlc_timeout = {
5658                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5659                 assert_eq!(node_txn[0].input.len(), 1);
5660                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5661                 check_spends!(node_txn[0], local_txn[0]);
5662                 node_txn[0].clone()
5663         };
5664
5665         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5666         nodes[0].block_notifier.block_connected(&Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
5667         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5668         expect_payment_failed!(nodes[0], our_payment_hash, true);
5669
5670         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5671         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5672         assert_eq!(spend_txn.len(), 3);
5673         assert_eq!(spend_txn[0], spend_txn[1]);
5674         check_spends!(spend_txn[0], local_txn[0]);
5675         check_spends!(spend_txn[2], htlc_timeout);
5676 }
5677
5678 #[test]
5679 fn test_key_derivation_params() {
5680         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5681         // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5682         // let us re-derive the channel key set to then derive a delayed_payment_key.
5683
5684         let chanmon_cfgs = create_chanmon_cfgs(3);
5685
5686         // We manually create the node configuration to backup the seed.
5687         let seed = [42; 32];
5688         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5689         let chan_monitor = test_utils::TestChannelMonitor::new(&chanmon_cfgs[0].chain_monitor, &chanmon_cfgs[0].tx_broadcaster, &chanmon_cfgs[0].logger, &chanmon_cfgs[0].fee_estimator);
5690         let node = NodeCfg { chain_monitor: &chanmon_cfgs[0].chain_monitor, logger: &chanmon_cfgs[0].logger, tx_broadcaster: &chanmon_cfgs[0].tx_broadcaster, fee_estimator: &chanmon_cfgs[0].fee_estimator, chan_monitor, keys_manager, node_seed: seed };
5691         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5692         node_cfgs.remove(0);
5693         node_cfgs.insert(0, node);
5694
5695         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5696         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5697
5698         // Create some initial channels
5699         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5700         // for node 0
5701         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5702         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5703         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5704
5705         let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5706         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5707         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5708         assert_eq!(local_txn_1[0].input.len(), 1);
5709         check_spends!(local_txn_1[0], chan_1.3);
5710
5711         // We check funding pubkey are unique
5712         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]));
5713         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]));
5714         if from_0_funding_key_0 == from_1_funding_key_0
5715             || from_0_funding_key_0 == from_1_funding_key_1
5716             || from_0_funding_key_1 == from_1_funding_key_0
5717             || from_0_funding_key_1 == from_1_funding_key_1 {
5718                 panic!("Funding pubkeys aren't unique");
5719         }
5720
5721         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5722         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5723         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![local_txn_1[0].clone()] }, 200);
5724         check_closed_broadcast!(nodes[0], false);
5725         check_added_monitors!(nodes[0], 1);
5726
5727         let htlc_timeout = {
5728                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5729                 assert_eq!(node_txn[0].input.len(), 1);
5730                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5731                 check_spends!(node_txn[0], local_txn_1[0]);
5732                 node_txn[0].clone()
5733         };
5734
5735         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5736         nodes[0].block_notifier.block_connected(&Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
5737         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5738         expect_payment_failed!(nodes[0], our_payment_hash, true);
5739
5740         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5741         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5742         let spend_txn = check_spendable_outputs!(nodes[0], 1, new_keys_manager, 100000);
5743         assert_eq!(spend_txn.len(), 3);
5744         assert_eq!(spend_txn[0], spend_txn[1]);
5745         check_spends!(spend_txn[0], local_txn_1[0]);
5746         check_spends!(spend_txn[2], htlc_timeout);
5747 }
5748
5749 #[test]
5750 fn test_static_output_closing_tx() {
5751         let chanmon_cfgs = create_chanmon_cfgs(2);
5752         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5753         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5754         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5755
5756         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5757
5758         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
5759         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5760
5761         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5762         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![closing_tx.clone()] }, 0);
5763         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
5764
5765         let spend_txn = check_spendable_outputs!(nodes[0], 2, node_cfgs[0].keys_manager, 100000);
5766         assert_eq!(spend_txn.len(), 1);
5767         check_spends!(spend_txn[0], closing_tx);
5768
5769         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![closing_tx.clone()] }, 0);
5770         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
5771
5772         let spend_txn = check_spendable_outputs!(nodes[1], 2, node_cfgs[1].keys_manager, 100000);
5773         assert_eq!(spend_txn.len(), 1);
5774         check_spends!(spend_txn[0], closing_tx);
5775 }
5776
5777 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5778         let chanmon_cfgs = create_chanmon_cfgs(2);
5779         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5780         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5781         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5782         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5783
5784         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5785
5786         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5787         // present in B's local commitment transaction, but none of A's commitment transactions.
5788         assert!(nodes[1].node.claim_funds(our_payment_preimage, &None, if use_dust { 50_000 } else { 3_000_000 }));
5789         check_added_monitors!(nodes[1], 1);
5790
5791         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5792         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5793         let events = nodes[0].node.get_and_clear_pending_events();
5794         assert_eq!(events.len(), 1);
5795         match events[0] {
5796                 Event::PaymentSent { payment_preimage } => {
5797                         assert_eq!(payment_preimage, our_payment_preimage);
5798                 },
5799                 _ => panic!("Unexpected event"),
5800         }
5801
5802         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5803         check_added_monitors!(nodes[0], 1);
5804         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5805         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5806         check_added_monitors!(nodes[1], 1);
5807
5808         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5809         for i in 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + CHAN_CONFIRM_DEPTH + 1 {
5810                 nodes[1].block_notifier.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
5811                 header.prev_blockhash = header.block_hash();
5812         }
5813         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5814         check_closed_broadcast!(nodes[1], false);
5815         check_added_monitors!(nodes[1], 1);
5816 }
5817
5818 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5819         let chanmon_cfgs = create_chanmon_cfgs(2);
5820         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5821         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5822         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5823         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5824         let logger = test_utils::TestLogger::new();
5825
5826         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5827         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5828         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();
5829         nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
5830         check_added_monitors!(nodes[0], 1);
5831
5832         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5833
5834         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5835         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5836         // to "time out" the HTLC.
5837
5838         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5839
5840         for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5841                 nodes[0].block_notifier.block_connected(&Block { header, txdata: Vec::new()}, i);
5842                 header.prev_blockhash = header.block_hash();
5843         }
5844         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5845         check_closed_broadcast!(nodes[0], false);
5846         check_added_monitors!(nodes[0], 1);
5847 }
5848
5849 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5850         let chanmon_cfgs = create_chanmon_cfgs(3);
5851         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5852         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5853         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5854         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5855
5856         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5857         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5858         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5859         // actually revoked.
5860         let htlc_value = if use_dust { 50000 } else { 3000000 };
5861         let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5862         assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash, &None));
5863         expect_pending_htlcs_forwardable!(nodes[1]);
5864         check_added_monitors!(nodes[1], 1);
5865
5866         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5867         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5868         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5869         check_added_monitors!(nodes[0], 1);
5870         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5871         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5872         check_added_monitors!(nodes[1], 1);
5873         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5874         check_added_monitors!(nodes[1], 1);
5875         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5876
5877         if check_revoke_no_close {
5878                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5879                 check_added_monitors!(nodes[0], 1);
5880         }
5881
5882         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5883         for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5884                 nodes[0].block_notifier.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
5885                 header.prev_blockhash = header.block_hash();
5886         }
5887         if !check_revoke_no_close {
5888                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5889                 check_closed_broadcast!(nodes[0], false);
5890                 check_added_monitors!(nodes[0], 1);
5891         } else {
5892                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5893         }
5894 }
5895
5896 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5897 // There are only a few cases to test here:
5898 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5899 //    broadcastable commitment transactions result in channel closure,
5900 //  * its included in an unrevoked-but-previous remote commitment transaction,
5901 //  * its included in the latest remote or local commitment transactions.
5902 // We test each of the three possible commitment transactions individually and use both dust and
5903 // non-dust HTLCs.
5904 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5905 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5906 // tested for at least one of the cases in other tests.
5907 #[test]
5908 fn htlc_claim_single_commitment_only_a() {
5909         do_htlc_claim_local_commitment_only(true);
5910         do_htlc_claim_local_commitment_only(false);
5911
5912         do_htlc_claim_current_remote_commitment_only(true);
5913         do_htlc_claim_current_remote_commitment_only(false);
5914 }
5915
5916 #[test]
5917 fn htlc_claim_single_commitment_only_b() {
5918         do_htlc_claim_previous_remote_commitment_only(true, false);
5919         do_htlc_claim_previous_remote_commitment_only(false, false);
5920         do_htlc_claim_previous_remote_commitment_only(true, true);
5921         do_htlc_claim_previous_remote_commitment_only(false, true);
5922 }
5923
5924 #[test]
5925 #[should_panic]
5926 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5927         let chanmon_cfgs = create_chanmon_cfgs(2);
5928         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5929         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5930         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5931         //Force duplicate channel ids
5932         for node in nodes.iter() {
5933                 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5934         }
5935
5936         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5937         let channel_value_satoshis=10000;
5938         let push_msat=10001;
5939         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5940         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5941         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5942
5943         //Create a second channel with a channel_id collision
5944         assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5945 }
5946
5947 #[test]
5948 fn bolt2_open_channel_sending_node_checks_part2() {
5949         let chanmon_cfgs = create_chanmon_cfgs(2);
5950         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5951         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5952         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5953
5954         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5955         let channel_value_satoshis=2^24;
5956         let push_msat=10001;
5957         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5958
5959         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5960         let channel_value_satoshis=10000;
5961         // Test when push_msat is equal to 1000 * funding_satoshis.
5962         let push_msat=1000*channel_value_satoshis+1;
5963         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5964
5965         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5966         let channel_value_satoshis=10000;
5967         let push_msat=10001;
5968         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
5969         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5970         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5971
5972         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5973         // 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
5974         assert!(node0_to_1_send_open_channel.channel_flags<=1);
5975
5976         // 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.
5977         assert!(BREAKDOWN_TIMEOUT>0);
5978         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5979
5980         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5981         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5982         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5983
5984         // 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.
5985         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5986         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5987         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5988         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5989         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5990 }
5991
5992 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5993 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5994 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5995 // is no longer affordable once it's freed.
5996 #[test]
5997 fn test_fail_holding_cell_htlc_upon_free() {
5998         let chanmon_cfgs = create_chanmon_cfgs(2);
5999         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6000         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6001         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6002         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6003         let logger = test_utils::TestLogger::new();
6004
6005         // First nodes[0] generates an update_fee, setting the channel's
6006         // pending_update_fee.
6007         nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 20).unwrap();
6008         check_added_monitors!(nodes[0], 1);
6009
6010         let events = nodes[0].node.get_and_clear_pending_msg_events();
6011         assert_eq!(events.len(), 1);
6012         let (update_msg, commitment_signed) = match events[0] {
6013                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6014                         (update_fee.as_ref(), commitment_signed)
6015                 },
6016                 _ => panic!("Unexpected event"),
6017         };
6018
6019         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6020
6021         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6022         let channel_reserve = chan_stat.channel_reserve_msat;
6023         let feerate = get_feerate!(nodes[0], chan.2);
6024
6025         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6026         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6027         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1);
6028         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6029         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();
6030
6031         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6032         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6033         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6034         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6035
6036         // Flush the pending fee update.
6037         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6038         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6039         check_added_monitors!(nodes[1], 1);
6040         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6041         check_added_monitors!(nodes[0], 1);
6042
6043         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6044         // HTLC, but now that the fee has been raised the payment will now fail, causing
6045         // us to surface its failure to the user.
6046         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6047         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6048         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 1 HTLC updates".to_string(), 1);
6049         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);
6050         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6051
6052         // Check that the payment failed to be sent out.
6053         let events = nodes[0].node.get_and_clear_pending_events();
6054         assert_eq!(events.len(), 1);
6055         match &events[0] {
6056                 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6057                         assert_eq!(our_payment_hash.clone(), *payment_hash);
6058                         assert_eq!(*rejected_by_dest, false);
6059                         assert_eq!(*error_code, None);
6060                         assert_eq!(*error_data, None);
6061                 },
6062                 _ => panic!("Unexpected event"),
6063         }
6064 }
6065
6066 // Test that if multiple HTLCs are released from the holding cell and one is
6067 // valid but the other is no longer valid upon release, the valid HTLC can be
6068 // successfully completed while the other one fails as expected.
6069 #[test]
6070 fn test_free_and_fail_holding_cell_htlcs() {
6071         let chanmon_cfgs = create_chanmon_cfgs(2);
6072         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6073         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6074         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6075         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6076         let logger = test_utils::TestLogger::new();
6077
6078         // First nodes[0] generates an update_fee, setting the channel's
6079         // pending_update_fee.
6080         nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 200).unwrap();
6081         check_added_monitors!(nodes[0], 1);
6082
6083         let events = nodes[0].node.get_and_clear_pending_msg_events();
6084         assert_eq!(events.len(), 1);
6085         let (update_msg, commitment_signed) = match events[0] {
6086                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6087                         (update_fee.as_ref(), commitment_signed)
6088                 },
6089                 _ => panic!("Unexpected event"),
6090         };
6091
6092         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6093
6094         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6095         let channel_reserve = chan_stat.channel_reserve_msat;
6096         let feerate = get_feerate!(nodes[0], chan.2);
6097
6098         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6099         let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
6100         let amt_1 = 20000;
6101         let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
6102         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1) - amt_1;
6103         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6104         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();
6105         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();
6106
6107         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6108         nodes[0].node.send_payment(&route_1, payment_hash_1, &None).unwrap();
6109         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6110         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6111         nodes[0].node.send_payment(&route_2, payment_hash_2, &None).unwrap();
6112         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6113         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6114
6115         // Flush the pending fee update.
6116         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6117         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6118         check_added_monitors!(nodes[1], 1);
6119         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6120         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6121         check_added_monitors!(nodes[0], 2);
6122
6123         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6124         // but now that the fee has been raised the second payment will now fail, causing us
6125         // to surface its failure to the user. The first payment should succeed.
6126         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6127         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6128         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 2 HTLC updates".to_string(), 1);
6129         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);
6130         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6131
6132         // Check that the second payment failed to be sent out.
6133         let events = nodes[0].node.get_and_clear_pending_events();
6134         assert_eq!(events.len(), 1);
6135         match &events[0] {
6136                 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6137                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6138                         assert_eq!(*rejected_by_dest, false);
6139                         assert_eq!(*error_code, None);
6140                         assert_eq!(*error_data, None);
6141                 },
6142                 _ => panic!("Unexpected event"),
6143         }
6144
6145         // Complete the first payment and the RAA from the fee update.
6146         let (payment_event, send_raa_event) = {
6147                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6148                 assert_eq!(msgs.len(), 2);
6149                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6150         };
6151         let raa = match send_raa_event {
6152                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6153                 _ => panic!("Unexpected event"),
6154         };
6155         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6156         check_added_monitors!(nodes[1], 1);
6157         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6158         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6159         let events = nodes[1].node.get_and_clear_pending_events();
6160         assert_eq!(events.len(), 1);
6161         match events[0] {
6162                 Event::PendingHTLCsForwardable { .. } => {},
6163                 _ => panic!("Unexpected event"),
6164         }
6165         nodes[1].node.process_pending_htlc_forwards();
6166         let events = nodes[1].node.get_and_clear_pending_events();
6167         assert_eq!(events.len(), 1);
6168         match events[0] {
6169                 Event::PaymentReceived { .. } => {},
6170                 _ => panic!("Unexpected event"),
6171         }
6172         nodes[1].node.claim_funds(payment_preimage_1, &None, amt_1);
6173         check_added_monitors!(nodes[1], 1);
6174         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6175         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6176         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6177         let events = nodes[0].node.get_and_clear_pending_events();
6178         assert_eq!(events.len(), 1);
6179         match events[0] {
6180                 Event::PaymentSent { ref payment_preimage } => {
6181                         assert_eq!(*payment_preimage, payment_preimage_1);
6182                 }
6183                 _ => panic!("Unexpected event"),
6184         }
6185 }
6186
6187 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6188 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6189 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6190 // once it's freed.
6191 #[test]
6192 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6193         let chanmon_cfgs = create_chanmon_cfgs(3);
6194         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6195         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6196         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6197         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6198         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6199         let logger = test_utils::TestLogger::new();
6200
6201         // First nodes[1] generates an update_fee, setting the channel's
6202         // pending_update_fee.
6203         nodes[1].node.update_fee(chan_1_2.2, get_feerate!(nodes[1], chan_1_2.2) + 20).unwrap();
6204         check_added_monitors!(nodes[1], 1);
6205
6206         let events = nodes[1].node.get_and_clear_pending_msg_events();
6207         assert_eq!(events.len(), 1);
6208         let (update_msg, commitment_signed) = match events[0] {
6209                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6210                         (update_fee.as_ref(), commitment_signed)
6211                 },
6212                 _ => panic!("Unexpected event"),
6213         };
6214
6215         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6216
6217         let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6218         let channel_reserve = chan_stat.channel_reserve_msat;
6219         let feerate = get_feerate!(nodes[0], chan_0_1.2);
6220
6221         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6222         let feemsat = 239;
6223         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6224         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6225         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1) - total_routing_fee_msat;
6226         let payment_event = {
6227                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6228                 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();
6229                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6230                 check_added_monitors!(nodes[0], 1);
6231
6232                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6233                 assert_eq!(events.len(), 1);
6234
6235                 SendEvent::from_event(events.remove(0))
6236         };
6237         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6238         check_added_monitors!(nodes[1], 0);
6239         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6240         expect_pending_htlcs_forwardable!(nodes[1]);
6241
6242         chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6243         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6244
6245         // Flush the pending fee update.
6246         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6247         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6248         check_added_monitors!(nodes[2], 1);
6249         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6250         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6251         check_added_monitors!(nodes[1], 2);
6252
6253         // A final RAA message is generated to finalize the fee update.
6254         let events = nodes[1].node.get_and_clear_pending_msg_events();
6255         assert_eq!(events.len(), 1);
6256
6257         let raa_msg = match &events[0] {
6258                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6259                         msg.clone()
6260                 },
6261                 _ => panic!("Unexpected event"),
6262         };
6263
6264         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6265         check_added_monitors!(nodes[2], 1);
6266         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6267
6268         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6269         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6270         assert_eq!(process_htlc_forwards_event.len(), 1);
6271         match &process_htlc_forwards_event[0] {
6272                 &Event::PendingHTLCsForwardable { .. } => {},
6273                 _ => panic!("Unexpected event"),
6274         }
6275
6276         // In response, we call ChannelManager's process_pending_htlc_forwards
6277         nodes[1].node.process_pending_htlc_forwards();
6278         check_added_monitors!(nodes[1], 1);
6279
6280         // This causes the HTLC to be failed backwards.
6281         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6282         assert_eq!(fail_event.len(), 1);
6283         let (fail_msg, commitment_signed) = match &fail_event[0] {
6284                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6285                         assert_eq!(updates.update_add_htlcs.len(), 0);
6286                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6287                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6288                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6289                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6290                 },
6291                 _ => panic!("Unexpected event"),
6292         };
6293
6294         // Pass the failure messages back to nodes[0].
6295         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6296         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6297
6298         // Complete the HTLC failure+removal process.
6299         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6300         check_added_monitors!(nodes[0], 1);
6301         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6302         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6303         check_added_monitors!(nodes[1], 2);
6304         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6305         assert_eq!(final_raa_event.len(), 1);
6306         let raa = match &final_raa_event[0] {
6307                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6308                 _ => panic!("Unexpected event"),
6309         };
6310         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6311         let fail_msg_event = nodes[0].node.get_and_clear_pending_msg_events();
6312         assert_eq!(fail_msg_event.len(), 1);
6313         match &fail_msg_event[0] {
6314                 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6315                 _ => panic!("Unexpected event"),
6316         }
6317         let failure_event = nodes[0].node.get_and_clear_pending_events();
6318         assert_eq!(failure_event.len(), 1);
6319         match &failure_event[0] {
6320                 &Event::PaymentFailed { rejected_by_dest, .. } => {
6321                         assert!(!rejected_by_dest);
6322                 },
6323                 _ => panic!("Unexpected event"),
6324         }
6325         check_added_monitors!(nodes[0], 1);
6326 }
6327
6328 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6329 // 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.
6330 //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.
6331
6332 #[test]
6333 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6334         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6335         let chanmon_cfgs = create_chanmon_cfgs(2);
6336         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6337         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6338         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6339         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6340
6341         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6342         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6343         let logger = test_utils::TestLogger::new();
6344         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();
6345         route.paths[0][0].fee_msat = 100;
6346
6347         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6348                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6349         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6350         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6351 }
6352
6353 #[test]
6354 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6355         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6356         let chanmon_cfgs = create_chanmon_cfgs(2);
6357         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6358         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6359         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6360         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6361         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6362
6363         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6364         let logger = test_utils::TestLogger::new();
6365         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();
6366         route.paths[0][0].fee_msat = 0;
6367         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6368                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6369
6370         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6371         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6372 }
6373
6374 #[test]
6375 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6376         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6377         let chanmon_cfgs = create_chanmon_cfgs(2);
6378         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6379         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6380         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6381         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6382
6383         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6384         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6385         let logger = test_utils::TestLogger::new();
6386         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();
6387         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6388         check_added_monitors!(nodes[0], 1);
6389         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6390         updates.update_add_htlcs[0].amount_msat = 0;
6391
6392         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6393         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6394         check_closed_broadcast!(nodes[1], true).unwrap();
6395         check_added_monitors!(nodes[1], 1);
6396 }
6397
6398 #[test]
6399 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6400         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6401         //It is enforced when constructing a route.
6402         let chanmon_cfgs = create_chanmon_cfgs(2);
6403         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6404         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6405         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6406         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 0, InitFeatures::known(), InitFeatures::known());
6407         let logger = test_utils::TestLogger::new();
6408
6409         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6410
6411         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6412         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();
6413         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::RouteError { ref err },
6414                 assert_eq!(err, &"Channel CLTV overflowed?"));
6415 }
6416
6417 #[test]
6418 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6419         //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.
6420         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6421         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6422         let chanmon_cfgs = create_chanmon_cfgs(2);
6423         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6424         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6425         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6426         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6427         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6428
6429         let logger = test_utils::TestLogger::new();
6430         for i in 0..max_accepted_htlcs {
6431                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6432                 let payment_event = {
6433                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6434                         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();
6435                         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6436                         check_added_monitors!(nodes[0], 1);
6437
6438                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6439                         assert_eq!(events.len(), 1);
6440                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6441                                 assert_eq!(htlcs[0].htlc_id, i);
6442                         } else {
6443                                 assert!(false);
6444                         }
6445                         SendEvent::from_event(events.remove(0))
6446                 };
6447                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6448                 check_added_monitors!(nodes[1], 0);
6449                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6450
6451                 expect_pending_htlcs_forwardable!(nodes[1]);
6452                 expect_payment_received!(nodes[1], our_payment_hash, 100000);
6453         }
6454         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6455         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6456         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();
6457         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6458                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6459
6460         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6461         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6462 }
6463
6464 #[test]
6465 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6466         //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.
6467         let chanmon_cfgs = create_chanmon_cfgs(2);
6468         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6469         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6470         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6471         let channel_value = 100000;
6472         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6473         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6474
6475         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight, max_in_flight);
6476
6477         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6478         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6479         let logger = test_utils::TestLogger::new();
6480         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();
6481         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6482                 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)));
6483
6484         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6485         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);
6486
6487         send_payment(&nodes[0], &[&nodes[1]], max_in_flight, max_in_flight);
6488 }
6489
6490 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6491 #[test]
6492 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6493         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6494         let chanmon_cfgs = create_chanmon_cfgs(2);
6495         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6496         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6497         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6498         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6499         let htlc_minimum_msat: u64;
6500         {
6501                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6502                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6503                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6504         }
6505
6506         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6507         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6508         let logger = test_utils::TestLogger::new();
6509         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();
6510         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6511         check_added_monitors!(nodes[0], 1);
6512         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6513         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6514         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6515         assert!(nodes[1].node.list_channels().is_empty());
6516         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6517         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()));
6518         check_added_monitors!(nodes[1], 1);
6519 }
6520
6521 #[test]
6522 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6523         //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
6524         let chanmon_cfgs = create_chanmon_cfgs(2);
6525         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6526         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6527         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6528         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6529         let logger = test_utils::TestLogger::new();
6530
6531         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6532         let channel_reserve = chan_stat.channel_reserve_msat;
6533         let feerate = get_feerate!(nodes[0], chan.2);
6534         // The 2* and +1 are for the fee spike reserve.
6535         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1);
6536
6537         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6538         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6539         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6540         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();
6541         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6542         check_added_monitors!(nodes[0], 1);
6543         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6544
6545         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6546         // at this time channel-initiatee receivers are not required to enforce that senders
6547         // respect the fee_spike_reserve.
6548         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6549         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6550
6551         assert!(nodes[1].node.list_channels().is_empty());
6552         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6553         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6554         check_added_monitors!(nodes[1], 1);
6555 }
6556
6557 #[test]
6558 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6559         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6560         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6561         let chanmon_cfgs = create_chanmon_cfgs(2);
6562         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6563         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6564         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6565         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6566         let logger = test_utils::TestLogger::new();
6567
6568         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6569         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6570
6571         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6572         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();
6573
6574         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
6575         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6576         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &None, cur_height).unwrap();
6577         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6578
6579         let mut msg = msgs::UpdateAddHTLC {
6580                 channel_id: chan.2,
6581                 htlc_id: 0,
6582                 amount_msat: 1000,
6583                 payment_hash: our_payment_hash,
6584                 cltv_expiry: htlc_cltv,
6585                 onion_routing_packet: onion_packet.clone(),
6586         };
6587
6588         for i in 0..super::channel::OUR_MAX_HTLCS {
6589                 msg.htlc_id = i as u64;
6590                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6591         }
6592         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6593         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6594
6595         assert!(nodes[1].node.list_channels().is_empty());
6596         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6597         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6598         check_added_monitors!(nodes[1], 1);
6599 }
6600
6601 #[test]
6602 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6603         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6604         let chanmon_cfgs = create_chanmon_cfgs(2);
6605         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6606         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6607         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6608         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6609         let logger = test_utils::TestLogger::new();
6610
6611         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6612         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6613         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();
6614         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6615         check_added_monitors!(nodes[0], 1);
6616         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6617         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6618         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6619
6620         assert!(nodes[1].node.list_channels().is_empty());
6621         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6622         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6623         check_added_monitors!(nodes[1], 1);
6624 }
6625
6626 #[test]
6627 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6628         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6629         let chanmon_cfgs = create_chanmon_cfgs(2);
6630         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6631         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6632         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6633         let logger = test_utils::TestLogger::new();
6634
6635         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6636         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6637         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6638         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();
6639         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6640         check_added_monitors!(nodes[0], 1);
6641         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6642         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6643         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6644
6645         assert!(nodes[1].node.list_channels().is_empty());
6646         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6647         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6648         check_added_monitors!(nodes[1], 1);
6649 }
6650
6651 #[test]
6652 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6653         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6654         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6655         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6656         let chanmon_cfgs = create_chanmon_cfgs(2);
6657         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6658         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6659         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6660         let logger = test_utils::TestLogger::new();
6661
6662         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6663         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6664         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6665         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();
6666         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6667         check_added_monitors!(nodes[0], 1);
6668         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6669         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6670
6671         //Disconnect and Reconnect
6672         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6673         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6674         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6675         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6676         assert_eq!(reestablish_1.len(), 1);
6677         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6678         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6679         assert_eq!(reestablish_2.len(), 1);
6680         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6681         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6682         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6683         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6684
6685         //Resend HTLC
6686         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6687         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6688         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6689         check_added_monitors!(nodes[1], 1);
6690         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6691
6692         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6693
6694         assert!(nodes[1].node.list_channels().is_empty());
6695         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6696         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6697         check_added_monitors!(nodes[1], 1);
6698 }
6699
6700 #[test]
6701 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6702         //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.
6703
6704         let chanmon_cfgs = create_chanmon_cfgs(2);
6705         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6706         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6707         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6708         let logger = test_utils::TestLogger::new();
6709         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6710         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6711         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6712         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();
6713         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6714
6715         check_added_monitors!(nodes[0], 1);
6716         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6717         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6718
6719         let update_msg = msgs::UpdateFulfillHTLC{
6720                 channel_id: chan.2,
6721                 htlc_id: 0,
6722                 payment_preimage: our_payment_preimage,
6723         };
6724
6725         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6726
6727         assert!(nodes[0].node.list_channels().is_empty());
6728         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6729         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()));
6730         check_added_monitors!(nodes[0], 1);
6731 }
6732
6733 #[test]
6734 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6735         //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.
6736
6737         let chanmon_cfgs = create_chanmon_cfgs(2);
6738         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6739         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6740         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6741         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6742         let logger = test_utils::TestLogger::new();
6743
6744         let (_, 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         check_added_monitors!(nodes[0], 1);
6749         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6750         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6751
6752         let update_msg = msgs::UpdateFailHTLC{
6753                 channel_id: chan.2,
6754                 htlc_id: 0,
6755                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6756         };
6757
6758         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6759
6760         assert!(nodes[0].node.list_channels().is_empty());
6761         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6762         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()));
6763         check_added_monitors!(nodes[0], 1);
6764 }
6765
6766 #[test]
6767 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6768         //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.
6769
6770         let chanmon_cfgs = create_chanmon_cfgs(2);
6771         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6772         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6773         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6774         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6775         let logger = test_utils::TestLogger::new();
6776
6777         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6778         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6779         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();
6780         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6781         check_added_monitors!(nodes[0], 1);
6782         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6783         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6784
6785         let update_msg = msgs::UpdateFailMalformedHTLC{
6786                 channel_id: chan.2,
6787                 htlc_id: 0,
6788                 sha256_of_onion: [1; 32],
6789                 failure_code: 0x8000,
6790         };
6791
6792         nodes[0].node.handle_update_fail_malformed_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_incorrect_htlc_id() {
6802         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
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 nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6808         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6809
6810         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6811
6812         nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6813         check_added_monitors!(nodes[1], 1);
6814
6815         let events = nodes[1].node.get_and_clear_pending_msg_events();
6816         assert_eq!(events.len(), 1);
6817         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6818                 match events[0] {
6819                         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, .. } } => {
6820                                 assert!(update_add_htlcs.is_empty());
6821                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6822                                 assert!(update_fail_htlcs.is_empty());
6823                                 assert!(update_fail_malformed_htlcs.is_empty());
6824                                 assert!(update_fee.is_none());
6825                                 update_fulfill_htlcs[0].clone()
6826                         },
6827                         _ => panic!("Unexpected event"),
6828                 }
6829         };
6830
6831         update_fulfill_msg.htlc_id = 1;
6832
6833         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6834
6835         assert!(nodes[0].node.list_channels().is_empty());
6836         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6837         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6838         check_added_monitors!(nodes[0], 1);
6839 }
6840
6841 #[test]
6842 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6843         //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.
6844
6845         let chanmon_cfgs = create_chanmon_cfgs(2);
6846         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6847         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6848         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6849         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6850
6851         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6852
6853         nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6854         check_added_monitors!(nodes[1], 1);
6855
6856         let events = nodes[1].node.get_and_clear_pending_msg_events();
6857         assert_eq!(events.len(), 1);
6858         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6859                 match events[0] {
6860                         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, .. } } => {
6861                                 assert!(update_add_htlcs.is_empty());
6862                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6863                                 assert!(update_fail_htlcs.is_empty());
6864                                 assert!(update_fail_malformed_htlcs.is_empty());
6865                                 assert!(update_fee.is_none());
6866                                 update_fulfill_htlcs[0].clone()
6867                         },
6868                         _ => panic!("Unexpected event"),
6869                 }
6870         };
6871
6872         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6873
6874         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6875
6876         assert!(nodes[0].node.list_channels().is_empty());
6877         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6878         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6879         check_added_monitors!(nodes[0], 1);
6880 }
6881
6882 #[test]
6883 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6884         //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.
6885
6886         let chanmon_cfgs = create_chanmon_cfgs(2);
6887         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6888         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6889         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6890         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6891         let logger = test_utils::TestLogger::new();
6892
6893         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6894         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6895         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();
6896         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6897         check_added_monitors!(nodes[0], 1);
6898
6899         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6900         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6901
6902         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6903         check_added_monitors!(nodes[1], 0);
6904         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6905
6906         let events = nodes[1].node.get_and_clear_pending_msg_events();
6907
6908         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6909                 match events[0] {
6910                         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, .. } } => {
6911                                 assert!(update_add_htlcs.is_empty());
6912                                 assert!(update_fulfill_htlcs.is_empty());
6913                                 assert!(update_fail_htlcs.is_empty());
6914                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6915                                 assert!(update_fee.is_none());
6916                                 update_fail_malformed_htlcs[0].clone()
6917                         },
6918                         _ => panic!("Unexpected event"),
6919                 }
6920         };
6921         update_msg.failure_code &= !0x8000;
6922         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6923
6924         assert!(nodes[0].node.list_channels().is_empty());
6925         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6926         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6927         check_added_monitors!(nodes[0], 1);
6928 }
6929
6930 #[test]
6931 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6932         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6933         //    * 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.
6934
6935         let chanmon_cfgs = create_chanmon_cfgs(3);
6936         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6937         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6938         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6939         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6940         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6941         let logger = test_utils::TestLogger::new();
6942
6943         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6944
6945         //First hop
6946         let mut payment_event = {
6947                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6948                 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();
6949                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6950                 check_added_monitors!(nodes[0], 1);
6951                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6952                 assert_eq!(events.len(), 1);
6953                 SendEvent::from_event(events.remove(0))
6954         };
6955         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6956         check_added_monitors!(nodes[1], 0);
6957         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6958         expect_pending_htlcs_forwardable!(nodes[1]);
6959         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6960         assert_eq!(events_2.len(), 1);
6961         check_added_monitors!(nodes[1], 1);
6962         payment_event = SendEvent::from_event(events_2.remove(0));
6963         assert_eq!(payment_event.msgs.len(), 1);
6964
6965         //Second Hop
6966         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6967         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6968         check_added_monitors!(nodes[2], 0);
6969         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6970
6971         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6972         assert_eq!(events_3.len(), 1);
6973         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6974                 match events_3[0] {
6975                         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 } } => {
6976                                 assert!(update_add_htlcs.is_empty());
6977                                 assert!(update_fulfill_htlcs.is_empty());
6978                                 assert!(update_fail_htlcs.is_empty());
6979                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6980                                 assert!(update_fee.is_none());
6981                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6982                         },
6983                         _ => panic!("Unexpected event"),
6984                 }
6985         };
6986
6987         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6988
6989         check_added_monitors!(nodes[1], 0);
6990         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6991         expect_pending_htlcs_forwardable!(nodes[1]);
6992         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6993         assert_eq!(events_4.len(), 1);
6994
6995         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6996         match events_4[0] {
6997                 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, .. } } => {
6998                         assert!(update_add_htlcs.is_empty());
6999                         assert!(update_fulfill_htlcs.is_empty());
7000                         assert_eq!(update_fail_htlcs.len(), 1);
7001                         assert!(update_fail_malformed_htlcs.is_empty());
7002                         assert!(update_fee.is_none());
7003                 },
7004                 _ => panic!("Unexpected event"),
7005         };
7006
7007         check_added_monitors!(nodes[1], 1);
7008 }
7009
7010 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7011         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7012         // 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
7013         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7014
7015         let chanmon_cfgs = create_chanmon_cfgs(2);
7016         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7017         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7018         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7019         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7020
7021         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7022
7023         // We route 2 dust-HTLCs between A and B
7024         let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7025         let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7026         route_payment(&nodes[0], &[&nodes[1]], 1000000);
7027
7028         // Cache one local commitment tx as previous
7029         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7030
7031         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7032         assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2, &None));
7033         check_added_monitors!(nodes[1], 0);
7034         expect_pending_htlcs_forwardable!(nodes[1]);
7035         check_added_monitors!(nodes[1], 1);
7036
7037         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7038         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7039         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7040         check_added_monitors!(nodes[0], 1);
7041
7042         // Cache one local commitment tx as lastest
7043         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7044
7045         let events = nodes[0].node.get_and_clear_pending_msg_events();
7046         match events[0] {
7047                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7048                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7049                 },
7050                 _ => panic!("Unexpected event"),
7051         }
7052         match events[1] {
7053                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7054                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7055                 },
7056                 _ => panic!("Unexpected event"),
7057         }
7058
7059         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7060         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7061         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7062
7063         if announce_latest {
7064                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_last_commitment_tx[0].clone()]}, 1);
7065         } else {
7066                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_prev_commitment_tx[0].clone()]}, 1);
7067         }
7068
7069         check_closed_broadcast!(nodes[0], false);
7070         check_added_monitors!(nodes[0], 1);
7071
7072         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7073         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 1, true,  header.block_hash());
7074         let events = nodes[0].node.get_and_clear_pending_events();
7075         // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
7076         assert_eq!(events.len(), 2);
7077         let mut first_failed = false;
7078         for event in events {
7079                 match event {
7080                         Event::PaymentFailed { payment_hash, .. } => {
7081                                 if payment_hash == payment_hash_1 {
7082                                         assert!(!first_failed);
7083                                         first_failed = true;
7084                                 } else {
7085                                         assert_eq!(payment_hash, payment_hash_2);
7086                                 }
7087                         }
7088                         _ => panic!("Unexpected event"),
7089                 }
7090         }
7091 }
7092
7093 #[test]
7094 fn test_failure_delay_dust_htlc_local_commitment() {
7095         do_test_failure_delay_dust_htlc_local_commitment(true);
7096         do_test_failure_delay_dust_htlc_local_commitment(false);
7097 }
7098
7099 #[test]
7100 fn test_no_failure_dust_htlc_local_commitment() {
7101         // Transaction filters for failing back dust htlc based on local commitment txn infos has been
7102         // prone to error, we test here that a dummy transaction don't fail them.
7103
7104         let chanmon_cfgs = create_chanmon_cfgs(2);
7105         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7106         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7107         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7108         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7109
7110         // Rebalance a bit
7111         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7112
7113         let as_dust_limit = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7114         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7115
7116         // We route 2 dust-HTLCs between A and B
7117         let (preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7118         let (preimage_2, _) = route_payment(&nodes[1], &[&nodes[0]], as_dust_limit*1000);
7119
7120         // Build a dummy invalid transaction trying to spend a commitment tx
7121         let input = TxIn {
7122                 previous_output: BitcoinOutPoint { txid: chan.3.txid(), vout: 0 },
7123                 script_sig: Script::new(),
7124                 sequence: 0,
7125                 witness: Vec::new(),
7126         };
7127
7128         let outp = TxOut {
7129                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
7130                 value: 10000,
7131         };
7132
7133         let dummy_tx = Transaction {
7134                 version: 2,
7135                 lock_time: 0,
7136                 input: vec![input],
7137                 output: vec![outp]
7138         };
7139
7140         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7141         nodes[0].chan_monitor.simple_monitor.block_connected(&header, 1, &[&dummy_tx], &[1;1]);
7142         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7143         assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
7144         // We broadcast a few more block to check everything is all right
7145         connect_blocks(&nodes[0].block_notifier, 20, 1, true,  header.block_hash());
7146         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7147         assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
7148
7149         claim_payment(&nodes[0], &vec!(&nodes[1])[..], preimage_1, bs_dust_limit*1000);
7150         claim_payment(&nodes[1], &vec!(&nodes[0])[..], preimage_2, as_dust_limit*1000);
7151 }
7152
7153 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7154         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7155         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7156         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7157         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7158         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7159         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7160
7161         let chanmon_cfgs = create_chanmon_cfgs(3);
7162         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7163         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7164         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7165         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7166
7167         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7168
7169         let (_payment_preimage_1, dust_hash) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7170         let (_payment_preimage_2, non_dust_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7171
7172         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7173         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7174
7175         // We revoked bs_commitment_tx
7176         if revoked {
7177                 let (payment_preimage_3, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7178                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 1_000_000);
7179         }
7180
7181         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7182         let mut timeout_tx = Vec::new();
7183         if local {
7184                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7185                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_commitment_tx[0].clone()]}, 1);
7186                 check_closed_broadcast!(nodes[0], false);
7187                 check_added_monitors!(nodes[0], 1);
7188                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7189                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7190                 let parent_hash  = connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 2, true, header.block_hash());
7191                 expect_payment_failed!(nodes[0], dust_hash, true);
7192                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7193                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7194                 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7195                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7196                 nodes[0].block_notifier.block_connected(&Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
7197                 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7198                 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 8, true, header_3.block_hash());
7199                 expect_payment_failed!(nodes[0], non_dust_hash, true);
7200         } else {
7201                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7202                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![bs_commitment_tx[0].clone()]}, 1);
7203                 check_closed_broadcast!(nodes[0], false);
7204                 check_added_monitors!(nodes[0], 1);
7205                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7206                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7207                 let parent_hash  = connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 2, true, header.block_hash());
7208                 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7209                 if !revoked {
7210                         expect_payment_failed!(nodes[0], dust_hash, true);
7211                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7212                         // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7213                         nodes[0].block_notifier.block_connected(&Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
7214                         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7215                         let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7216                         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 8, true, header_3.block_hash());
7217                         expect_payment_failed!(nodes[0], non_dust_hash, true);
7218                 } else {
7219                         // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7220                         // commitment tx
7221                         let events = nodes[0].node.get_and_clear_pending_events();
7222                         assert_eq!(events.len(), 2);
7223                         let first;
7224                         match events[0] {
7225                                 Event::PaymentFailed { payment_hash, .. } => {
7226                                         if payment_hash == dust_hash { first = true; }
7227                                         else { first = false; }
7228                                 },
7229                                 _ => panic!("Unexpected event"),
7230                         }
7231                         match events[1] {
7232                                 Event::PaymentFailed { payment_hash, .. } => {
7233                                         if first { assert_eq!(payment_hash, non_dust_hash); }
7234                                         else { assert_eq!(payment_hash, dust_hash); }
7235                                 },
7236                                 _ => panic!("Unexpected event"),
7237                         }
7238                 }
7239         }
7240 }
7241
7242 #[test]
7243 fn test_sweep_outbound_htlc_failure_update() {
7244         do_test_sweep_outbound_htlc_failure_update(false, true);
7245         do_test_sweep_outbound_htlc_failure_update(false, false);
7246         do_test_sweep_outbound_htlc_failure_update(true, false);
7247 }
7248
7249 #[test]
7250 fn test_upfront_shutdown_script() {
7251         // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
7252         // enforce it at shutdown message
7253
7254         let mut config = UserConfig::default();
7255         config.channel_options.announced_channel = true;
7256         config.peer_channel_config_limits.force_announced_channel_preference = false;
7257         config.channel_options.commit_upfront_shutdown_pubkey = false;
7258         let user_cfgs = [None, Some(config), None];
7259         let chanmon_cfgs = create_chanmon_cfgs(3);
7260         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7261         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7262         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7263
7264         // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
7265         let flags = InitFeatures::known();
7266         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7267         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7268         let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7269         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7270         // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that  we disconnect peer
7271         nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
7272     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()));
7273         check_added_monitors!(nodes[2], 1);
7274
7275         // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
7276         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7277         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7278         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7279         // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
7280         nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
7281         let events = nodes[2].node.get_and_clear_pending_msg_events();
7282         assert_eq!(events.len(), 1);
7283         match events[0] {
7284                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7285                 _ => panic!("Unexpected event"),
7286         }
7287
7288         // We test that if case of peer non-signaling we don't enforce committed script at channel opening
7289         let flags_no = InitFeatures::known().clear_upfront_shutdown_script();
7290         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone());
7291         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7292         let mut node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
7293         node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7294         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_1_shutdown);
7295         let events = nodes[1].node.get_and_clear_pending_msg_events();
7296         assert_eq!(events.len(), 1);
7297         match events[0] {
7298                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7299                 _ => panic!("Unexpected event"),
7300         }
7301
7302         // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7303         // channel smoothly, opt-out is from channel initiator here
7304         let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone());
7305         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7306         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7307         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7308         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
7309         let events = nodes[0].node.get_and_clear_pending_msg_events();
7310         assert_eq!(events.len(), 1);
7311         match events[0] {
7312                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7313                 _ => panic!("Unexpected event"),
7314         }
7315
7316         //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7317         //// channel smoothly
7318         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone());
7319         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7320         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7321         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7322         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
7323         let events = nodes[0].node.get_and_clear_pending_msg_events();
7324         assert_eq!(events.len(), 2);
7325         match events[0] {
7326                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7327                 _ => panic!("Unexpected event"),
7328         }
7329         match events[1] {
7330                 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7331                 _ => panic!("Unexpected event"),
7332         }
7333 }
7334
7335 #[test]
7336 fn test_user_configurable_csv_delay() {
7337         // We test our channel constructors yield errors when we pass them absurd csv delay
7338
7339         let mut low_our_to_self_config = UserConfig::default();
7340         low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7341         let mut high_their_to_self_config = UserConfig::default();
7342         high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7343         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7344         let chanmon_cfgs = create_chanmon_cfgs(2);
7345         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7346         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7347         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7348
7349         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7350         let keys_manager: Arc<KeysInterface<ChanKeySigner = EnforcingChannelKeys>> = Arc::new(test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet));
7351         if let Err(error) = Channel::new_outbound(&&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &keys_manager, nodes[1].node.get_our_node_id(), 1000000, 1000000, 0, &low_our_to_self_config) {
7352                 match error {
7353                         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())); },
7354                         _ => panic!("Unexpected event"),
7355                 }
7356         } else { assert!(false) }
7357
7358         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7359         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7360         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7361         open_channel.to_self_delay = 200;
7362         if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &keys_manager, nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel, 0, &low_our_to_self_config) {
7363                 match error {
7364                         ChannelError::Close(err) => { assert!(regex::Regex::new(r"Configured with an unreasonable our_to_self_delay \(\d+\) putting user funds at risks").unwrap().is_match(err.as_str()));  },
7365                         _ => panic!("Unexpected event"),
7366                 }
7367         } else { assert!(false); }
7368
7369         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7370         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7371         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()));
7372         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7373         accept_channel.to_self_delay = 200;
7374         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7375         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7376                 match action {
7377                         &ErrorAction::SendErrorMessage { ref msg } => {
7378                                 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()));
7379                         },
7380                         _ => { assert!(false); }
7381                 }
7382         } else { assert!(false); }
7383
7384         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7385         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7386         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7387         open_channel.to_self_delay = 200;
7388         if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &keys_manager, nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel, 0, &high_their_to_self_config) {
7389                 match error {
7390                         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())); },
7391                         _ => panic!("Unexpected event"),
7392                 }
7393         } else { assert!(false); }
7394 }
7395
7396 #[test]
7397 fn test_data_loss_protect() {
7398         // We want to be sure that :
7399         // * we don't broadcast our Local Commitment Tx in case of fallen behind
7400         // * we close channel in case of detecting other being fallen behind
7401         // * we are able to claim our own outputs thanks to to_remote being static
7402         let keys_manager;
7403         let logger;
7404         let fee_estimator;
7405         let tx_broadcaster;
7406         let chain_monitor;
7407         let monitor;
7408         let node_state_0;
7409         let chanmon_cfgs = create_chanmon_cfgs(2);
7410         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7411         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7412         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7413
7414         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7415
7416         // Cache node A state before any channel update
7417         let previous_node_state = nodes[0].node.encode();
7418         let mut previous_chan_monitor_state = test_utils::TestVecWriter(Vec::new());
7419         nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut previous_chan_monitor_state).unwrap();
7420
7421         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7422         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7423
7424         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7425         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7426
7427         // Restore node A from previous state
7428         logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7429         let mut chan_monitor = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut ::std::io::Cursor::new(previous_chan_monitor_state.0)).unwrap().1;
7430         chain_monitor = ChainWatchInterfaceUtil::new(Network::Testnet);
7431         tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
7432         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
7433         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
7434         monitor = test_utils::TestChannelMonitor::new(&chain_monitor, &tx_broadcaster, &logger, &fee_estimator);
7435         node_state_0 = {
7436                 let mut channel_monitors = HashMap::new();
7437                 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chan_monitor);
7438                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut ::std::io::Cursor::new(previous_node_state), ChannelManagerReadArgs {
7439                         keys_manager: &keys_manager,
7440                         fee_estimator: &fee_estimator,
7441                         monitor: &monitor,
7442                         logger: &logger,
7443                         tx_broadcaster: &tx_broadcaster,
7444                         default_config: UserConfig::default(),
7445                         channel_monitors,
7446                 }).unwrap().1
7447         };
7448         nodes[0].node = &node_state_0;
7449         assert!(monitor.add_monitor(OutPoint { txid: chan.3.txid(), index: 0 }, chan_monitor).is_ok());
7450         nodes[0].chan_monitor = &monitor;
7451         nodes[0].chain_monitor = &chain_monitor;
7452
7453         nodes[0].block_notifier = BlockNotifier::new(&nodes[0].chain_monitor);
7454         nodes[0].block_notifier.register_listener(&nodes[0].chan_monitor.simple_monitor);
7455         nodes[0].block_notifier.register_listener(nodes[0].node);
7456
7457         check_added_monitors!(nodes[0], 1);
7458
7459         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7460         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7461
7462         let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7463
7464         // Check we don't broadcast any transactions following learning of per_commitment_point from B
7465         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7466         check_added_monitors!(nodes[0], 1);
7467
7468         {
7469                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7470                 assert_eq!(node_txn.len(), 0);
7471         }
7472
7473         let mut reestablish_1 = Vec::with_capacity(1);
7474         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7475                 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7476                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7477                         reestablish_1.push(msg.clone());
7478                 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7479                 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7480                         match action {
7481                                 &ErrorAction::SendErrorMessage { ref msg } => {
7482                                         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");
7483                                 },
7484                                 _ => panic!("Unexpected event!"),
7485                         }
7486                 } else {
7487                         panic!("Unexpected event")
7488                 }
7489         }
7490
7491         // Check we close channel detecting A is fallen-behind
7492         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7493         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7494         check_added_monitors!(nodes[1], 1);
7495
7496
7497         // Check A is able to claim to_remote output
7498         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7499         assert_eq!(node_txn.len(), 1);
7500         check_spends!(node_txn[0], chan.3);
7501         assert_eq!(node_txn[0].output.len(), 2);
7502         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
7503         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()]}, 0);
7504         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
7505         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
7506         assert_eq!(spend_txn.len(), 1);
7507         check_spends!(spend_txn[0], node_txn[0]);
7508 }
7509
7510 #[test]
7511 fn test_check_htlc_underpaying() {
7512         // Send payment through A -> B but A is maliciously
7513         // sending a probe payment (i.e less than expected value0
7514         // to B, B should refuse payment.
7515
7516         let chanmon_cfgs = create_chanmon_cfgs(2);
7517         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7518         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7519         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7520
7521         // Create some initial channels
7522         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7523
7524         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 10_000);
7525
7526         // Node 3 is expecting payment of 100_000 but receive 10_000,
7527         // fail htlc like we didn't know the preimage.
7528         nodes[1].node.claim_funds(payment_preimage, &None, 100_000);
7529         nodes[1].node.process_pending_htlc_forwards();
7530
7531         let events = nodes[1].node.get_and_clear_pending_msg_events();
7532         assert_eq!(events.len(), 1);
7533         let (update_fail_htlc, commitment_signed) = match events[0] {
7534                 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 } } => {
7535                         assert!(update_add_htlcs.is_empty());
7536                         assert!(update_fulfill_htlcs.is_empty());
7537                         assert_eq!(update_fail_htlcs.len(), 1);
7538                         assert!(update_fail_malformed_htlcs.is_empty());
7539                         assert!(update_fee.is_none());
7540                         (update_fail_htlcs[0].clone(), commitment_signed)
7541                 },
7542                 _ => panic!("Unexpected event"),
7543         };
7544         check_added_monitors!(nodes[1], 1);
7545
7546         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7547         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7548
7549         // 10_000 msat as u64, followed by a height of 99 as u32
7550         let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7551         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(99));
7552         expect_payment_failed!(nodes[0], payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7553         nodes[1].node.get_and_clear_pending_events();
7554 }
7555
7556 #[test]
7557 fn test_announce_disable_channels() {
7558         // Create 2 channels between A and B. Disconnect B. Call timer_chan_freshness_every_min and check for generated
7559         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7560
7561         let chanmon_cfgs = create_chanmon_cfgs(2);
7562         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7563         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7564         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7565
7566         let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7567         let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7568         let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7569
7570         // Disconnect peers
7571         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7572         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7573
7574         nodes[0].node.timer_chan_freshness_every_min(); // dirty -> stagged
7575         nodes[0].node.timer_chan_freshness_every_min(); // staged -> fresh
7576         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7577         assert_eq!(msg_events.len(), 3);
7578         for e in msg_events {
7579                 match e {
7580                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7581                                 let short_id = msg.contents.short_channel_id;
7582                                 // Check generated channel_update match list in PendingChannelUpdate
7583                                 if short_id != short_id_1 && short_id != short_id_2 && short_id != short_id_3 {
7584                                         panic!("Generated ChannelUpdate for wrong chan!");
7585                                 }
7586                         },
7587                         _ => panic!("Unexpected event"),
7588                 }
7589         }
7590         // Reconnect peers
7591         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7592         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7593         assert_eq!(reestablish_1.len(), 3);
7594         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7595         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7596         assert_eq!(reestablish_2.len(), 3);
7597
7598         // Reestablish chan_1
7599         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7600         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7601         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7602         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7603         // Reestablish chan_2
7604         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7605         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7606         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7607         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7608         // Reestablish chan_3
7609         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7610         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7611         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7612         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7613
7614         nodes[0].node.timer_chan_freshness_every_min();
7615         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7616 }
7617
7618 #[test]
7619 fn test_bump_penalty_txn_on_revoked_commitment() {
7620         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7621         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7622
7623         let chanmon_cfgs = create_chanmon_cfgs(2);
7624         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7625         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7626         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7627
7628         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7629         let logger = test_utils::TestLogger::new();
7630
7631
7632         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7633         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
7634         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();
7635         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7636
7637         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7638         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7639         assert_eq!(revoked_txn[0].output.len(), 4);
7640         assert_eq!(revoked_txn[0].input.len(), 1);
7641         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7642         let revoked_txid = revoked_txn[0].txid();
7643
7644         let mut penalty_sum = 0;
7645         for outp in revoked_txn[0].output.iter() {
7646                 if outp.script_pubkey.is_v0_p2wsh() {
7647                         penalty_sum += outp.value;
7648                 }
7649         }
7650
7651         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7652         let header_114 = connect_blocks(&nodes[1].block_notifier, 114, 0, false, Default::default());
7653
7654         // Actually revoke tx by claiming a HTLC
7655         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7656         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7657         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_txn[0].clone()] }, 115);
7658         check_added_monitors!(nodes[1], 1);
7659
7660         // One or more justice tx should have been broadcast, check it
7661         let penalty_1;
7662         let feerate_1;
7663         {
7664                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7665                 assert_eq!(node_txn.len(), 3); // justice tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout (broadcasted from ChannelManager)
7666                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7667                 assert_eq!(node_txn[0].output.len(), 1);
7668                 check_spends!(node_txn[0], revoked_txn[0]);
7669                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7670                 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7671                 penalty_1 = node_txn[0].txid();
7672                 node_txn.clear();
7673         };
7674
7675         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7676         let header = connect_blocks(&nodes[1].block_notifier, 3, 115,  true, header.block_hash());
7677         let mut penalty_2 = penalty_1;
7678         let mut feerate_2 = 0;
7679         {
7680                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7681                 assert_eq!(node_txn.len(), 1);
7682                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7683                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7684                         assert_eq!(node_txn[0].output.len(), 1);
7685                         check_spends!(node_txn[0], revoked_txn[0]);
7686                         penalty_2 = node_txn[0].txid();
7687                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7688                         assert_ne!(penalty_2, penalty_1);
7689                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7690                         feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7691                         // Verify 25% bump heuristic
7692                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7693                         node_txn.clear();
7694                 }
7695         }
7696         assert_ne!(feerate_2, 0);
7697
7698         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7699         connect_blocks(&nodes[1].block_notifier, 3, 118, true, header);
7700         let penalty_3;
7701         let mut feerate_3 = 0;
7702         {
7703                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7704                 assert_eq!(node_txn.len(), 1);
7705                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7706                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7707                         assert_eq!(node_txn[0].output.len(), 1);
7708                         check_spends!(node_txn[0], revoked_txn[0]);
7709                         penalty_3 = node_txn[0].txid();
7710                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7711                         assert_ne!(penalty_3, penalty_2);
7712                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7713                         feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7714                         // Verify 25% bump heuristic
7715                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7716                         node_txn.clear();
7717                 }
7718         }
7719         assert_ne!(feerate_3, 0);
7720
7721         nodes[1].node.get_and_clear_pending_events();
7722         nodes[1].node.get_and_clear_pending_msg_events();
7723 }
7724
7725 #[test]
7726 fn test_bump_penalty_txn_on_revoked_htlcs() {
7727         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7728         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7729
7730         let chanmon_cfgs = create_chanmon_cfgs(2);
7731         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7732         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7733         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7734
7735         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7736         // Lock HTLC in both directions
7737         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3_000_000).0;
7738         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7739
7740         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7741         assert_eq!(revoked_local_txn[0].input.len(), 1);
7742         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7743
7744         // Revoke local commitment tx
7745         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7746
7747         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7748         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7749         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
7750         check_closed_broadcast!(nodes[1], false);
7751         check_added_monitors!(nodes[1], 1);
7752
7753         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7754         assert_eq!(revoked_htlc_txn.len(), 4);
7755         if revoked_htlc_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7756                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7757                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7758                 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7759                 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7760                 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7761         } else if revoked_htlc_txn[1].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7762                 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7763                 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7764                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7765                 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7766                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7767         }
7768
7769         // Broadcast set of revoked txn on A
7770         let header_128 = connect_blocks(&nodes[0].block_notifier, 128, 0, true, header.block_hash());
7771         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7772
7773         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7774         nodes[0].block_notifier.block_connected(&Block { header: header_129, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()] }, 129);
7775         let first;
7776         let feerate_1;
7777         let penalty_txn;
7778         {
7779                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7780                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7781                 // Verify claim tx are spending revoked HTLC txn
7782                 assert_eq!(node_txn[4].input.len(), 2);
7783                 assert_eq!(node_txn[4].output.len(), 1);
7784                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7785                 first = node_txn[4].txid();
7786                 // Store both feerates for later comparison
7787                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[4].output[0].value;
7788                 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7789                 penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7790                 node_txn.clear();
7791         }
7792
7793         // Connect three more block to see if bumped penalty are issued for HTLC txn
7794         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7795         nodes[0].block_notifier.block_connected(&Block { header: header_130, txdata: penalty_txn }, 130);
7796         {
7797                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7798                 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7799
7800                 check_spends!(node_txn[0], revoked_local_txn[0]);
7801                 check_spends!(node_txn[1], revoked_local_txn[0]);
7802
7803                 node_txn.clear();
7804         };
7805
7806         // Few more blocks to confirm penalty txn
7807         let header_135 = connect_blocks(&nodes[0].block_notifier, 5, 130, true, header_130.block_hash());
7808         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7809         let header_144 = connect_blocks(&nodes[0].block_notifier, 9, 135, true, header_135);
7810         let node_txn = {
7811                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7812                 assert_eq!(node_txn.len(), 1);
7813
7814                 assert_eq!(node_txn[0].input.len(), 2);
7815                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7816                 // Verify bumped tx is different and 25% bump heuristic
7817                 assert_ne!(first, node_txn[0].txid());
7818                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7819                 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7820                 assert!(feerate_2 * 100 > feerate_1 * 125);
7821                 let txn = vec![node_txn[0].clone()];
7822                 node_txn.clear();
7823                 txn
7824         };
7825         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7826         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7827         nodes[0].block_notifier.block_connected(&Block { header: header_145, txdata: node_txn }, 145);
7828         connect_blocks(&nodes[0].block_notifier, 20, 145, true, header_145.block_hash());
7829         {
7830                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7831                 // We verify than no new transaction has been broadcast because previously
7832                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7833                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7834                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7835                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7836                 // up bumped justice generation.
7837                 assert_eq!(node_txn.len(), 0);
7838                 node_txn.clear();
7839         }
7840         check_closed_broadcast!(nodes[0], false);
7841         check_added_monitors!(nodes[0], 1);
7842 }
7843
7844 #[test]
7845 fn test_bump_penalty_txn_on_remote_commitment() {
7846         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7847         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7848
7849         // Create 2 HTLCs
7850         // Provide preimage for one
7851         // Check aggregation
7852
7853         let chanmon_cfgs = create_chanmon_cfgs(2);
7854         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7855         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7856         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7857
7858         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7859         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7860         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7861
7862         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7863         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7864         assert_eq!(remote_txn[0].output.len(), 4);
7865         assert_eq!(remote_txn[0].input.len(), 1);
7866         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7867
7868         // Claim a HTLC without revocation (provide B monitor with preimage)
7869         nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000);
7870         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7871         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
7872         check_added_monitors!(nodes[1], 2);
7873
7874         // One or more claim tx should have been broadcast, check it
7875         let timeout;
7876         let preimage;
7877         let feerate_timeout;
7878         let feerate_preimage;
7879         {
7880                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7881                 assert_eq!(node_txn.len(), 5); // 2 * claim tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout + local HTLC-success (broadcasted from ChannelManager)
7882                 assert_eq!(node_txn[0].input.len(), 1);
7883                 assert_eq!(node_txn[1].input.len(), 1);
7884                 check_spends!(node_txn[0], remote_txn[0]);
7885                 check_spends!(node_txn[1], remote_txn[0]);
7886                 check_spends!(node_txn[2], chan.3);
7887                 check_spends!(node_txn[3], node_txn[2]);
7888                 check_spends!(node_txn[4], node_txn[2]);
7889                 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7890                         timeout = node_txn[0].txid();
7891                         let index = node_txn[0].input[0].previous_output.vout;
7892                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7893                         feerate_timeout = fee * 1000 / node_txn[0].get_weight() as u64;
7894
7895                         preimage = node_txn[1].txid();
7896                         let index = node_txn[1].input[0].previous_output.vout;
7897                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7898                         feerate_preimage = fee * 1000 / node_txn[1].get_weight() as u64;
7899                 } else {
7900                         timeout = node_txn[1].txid();
7901                         let index = node_txn[1].input[0].previous_output.vout;
7902                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7903                         feerate_timeout = fee * 1000 / node_txn[1].get_weight() as u64;
7904
7905                         preimage = node_txn[0].txid();
7906                         let index = node_txn[0].input[0].previous_output.vout;
7907                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7908                         feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7909                 }
7910                 node_txn.clear();
7911         };
7912         assert_ne!(feerate_timeout, 0);
7913         assert_ne!(feerate_preimage, 0);
7914
7915         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7916         connect_blocks(&nodes[1].block_notifier, 15, 1,  true, header.block_hash());
7917         {
7918                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7919                 assert_eq!(node_txn.len(), 2);
7920                 assert_eq!(node_txn[0].input.len(), 1);
7921                 assert_eq!(node_txn[1].input.len(), 1);
7922                 check_spends!(node_txn[0], remote_txn[0]);
7923                 check_spends!(node_txn[1], remote_txn[0]);
7924                 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7925                         let index = node_txn[0].input[0].previous_output.vout;
7926                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7927                         let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7928                         assert!(new_feerate * 100 > feerate_timeout * 125);
7929                         assert_ne!(timeout, node_txn[0].txid());
7930
7931                         let index = node_txn[1].input[0].previous_output.vout;
7932                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7933                         let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7934                         assert!(new_feerate * 100 > feerate_preimage * 125);
7935                         assert_ne!(preimage, node_txn[1].txid());
7936                 } else {
7937                         let index = node_txn[1].input[0].previous_output.vout;
7938                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7939                         let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7940                         assert!(new_feerate * 100 > feerate_timeout * 125);
7941                         assert_ne!(timeout, node_txn[1].txid());
7942
7943                         let index = node_txn[0].input[0].previous_output.vout;
7944                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7945                         let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7946                         assert!(new_feerate * 100 > feerate_preimage * 125);
7947                         assert_ne!(preimage, node_txn[0].txid());
7948                 }
7949                 node_txn.clear();
7950         }
7951
7952         nodes[1].node.get_and_clear_pending_events();
7953         nodes[1].node.get_and_clear_pending_msg_events();
7954 }
7955
7956 #[test]
7957 fn test_set_outpoints_partial_claiming() {
7958         // - remote party claim tx, new bump tx
7959         // - disconnect remote claiming tx, new bump
7960         // - disconnect tx, see no tx anymore
7961         let chanmon_cfgs = create_chanmon_cfgs(2);
7962         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7963         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7964         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7965
7966         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7967         let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7968         let payment_preimage_2 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7969
7970         // Remote commitment txn with 4 outputs: to_local, to_remote, 2 outgoing HTLC
7971         let remote_txn = get_local_commitment_txn!(nodes[1], chan.2);
7972         assert_eq!(remote_txn.len(), 3);
7973         assert_eq!(remote_txn[0].output.len(), 4);
7974         assert_eq!(remote_txn[0].input.len(), 1);
7975         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7976         check_spends!(remote_txn[1], remote_txn[0]);
7977         check_spends!(remote_txn[2], remote_txn[0]);
7978
7979         // Connect blocks on node A to advance height towards TEST_FINAL_CLTV
7980         let prev_header_100 = connect_blocks(&nodes[1].block_notifier, 100, 0, false, Default::default());
7981         // Provide node A with both preimage
7982         nodes[0].node.claim_funds(payment_preimage_1, &None, 3_000_000);
7983         nodes[0].node.claim_funds(payment_preimage_2, &None, 3_000_000);
7984         check_added_monitors!(nodes[0], 2);
7985         nodes[0].node.get_and_clear_pending_events();
7986         nodes[0].node.get_and_clear_pending_msg_events();
7987
7988         // Connect blocks on node A commitment transaction
7989         let header = BlockHeader { version: 0x20000000, prev_blockhash: prev_header_100, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7990         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 101);
7991         check_closed_broadcast!(nodes[0], false);
7992         check_added_monitors!(nodes[0], 1);
7993         // Verify node A broadcast tx claiming both HTLCs
7994         {
7995                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7996                 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-Success*2
7997                 assert_eq!(node_txn.len(), 4);
7998                 check_spends!(node_txn[0], remote_txn[0]);
7999                 check_spends!(node_txn[1], chan.3);
8000                 check_spends!(node_txn[2], node_txn[1]);
8001                 check_spends!(node_txn[3], node_txn[1]);
8002                 assert_eq!(node_txn[0].input.len(), 2);
8003                 node_txn.clear();
8004         }
8005
8006         // Connect blocks on node B
8007         connect_blocks(&nodes[1].block_notifier, 135, 0, false, Default::default());
8008         check_closed_broadcast!(nodes[1], false);
8009         check_added_monitors!(nodes[1], 1);
8010         // Verify node B broadcast 2 HTLC-timeout txn
8011         let partial_claim_tx = {
8012                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8013                 assert_eq!(node_txn.len(), 3);
8014                 check_spends!(node_txn[1], node_txn[0]);
8015                 check_spends!(node_txn[2], node_txn[0]);
8016                 assert_eq!(node_txn[1].input.len(), 1);
8017                 assert_eq!(node_txn[2].input.len(), 1);
8018                 node_txn[1].clone()
8019         };
8020
8021         // Broadcast partial claim on node A, should regenerate a claiming tx with HTLC dropped
8022         let header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8023         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![partial_claim_tx.clone()] }, 102);
8024         {
8025                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8026                 assert_eq!(node_txn.len(), 1);
8027                 check_spends!(node_txn[0], remote_txn[0]);
8028                 assert_eq!(node_txn[0].input.len(), 1); //dropped HTLC
8029                 node_txn.clear();
8030         }
8031         nodes[0].node.get_and_clear_pending_msg_events();
8032
8033         // Disconnect last block on node A, should regenerate a claiming tx with HTLC dropped
8034         nodes[0].block_notifier.block_disconnected(&header, 102);
8035         {
8036                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8037                 assert_eq!(node_txn.len(), 1);
8038                 check_spends!(node_txn[0], remote_txn[0]);
8039                 assert_eq!(node_txn[0].input.len(), 2); //resurrected HTLC
8040                 node_txn.clear();
8041         }
8042
8043         //// Disconnect one more block and then reconnect multiple no transaction should be generated
8044         nodes[0].block_notifier.block_disconnected(&header, 101);
8045         connect_blocks(&nodes[1].block_notifier, 15, 101, false, prev_header_100);
8046         {
8047                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8048                 assert_eq!(node_txn.len(), 0);
8049                 node_txn.clear();
8050         }
8051 }
8052
8053 #[test]
8054 fn test_counterparty_raa_skip_no_crash() {
8055         // Previously, if our counterparty sent two RAAs in a row without us having provided a
8056         // commitment transaction, we would have happily carried on and provided them the next
8057         // commitment transaction based on one RAA forward. This would probably eventually have led to
8058         // channel closure, but it would not have resulted in funds loss. Still, our
8059         // EnforcingChannelKeys would have paniced as it doesn't like jumps into the future. Here, we
8060         // check simply that the channel is closed in response to such an RAA, but don't check whether
8061         // we decide to punish our counterparty for revoking their funds (as we don't currently
8062         // implement that).
8063         let chanmon_cfgs = create_chanmon_cfgs(2);
8064         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8065         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8066         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8067         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8068
8069         let mut guard = nodes[0].node.channel_state.lock().unwrap();
8070         let keys = &guard.by_id.get_mut(&channel_id).unwrap().holder_keys;
8071         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8072         let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8073                 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8074         let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8075
8076         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8077                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8078         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8079         check_added_monitors!(nodes[1], 1);
8080 }
8081
8082 #[test]
8083 fn test_bump_txn_sanitize_tracking_maps() {
8084         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8085         // verify we clean then right after expiration of ANTI_REORG_DELAY.
8086
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
8092         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8093         // Lock HTLC in both directions
8094         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8095         route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8096
8097         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8098         assert_eq!(revoked_local_txn[0].input.len(), 1);
8099         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8100
8101         // Revoke local commitment tx
8102         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 9_000_000);
8103
8104         // Broadcast set of revoked txn on A
8105         let header_128 = connect_blocks(&nodes[0].block_notifier, 128, 0,  false, Default::default());
8106         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8107
8108         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8109         nodes[0].block_notifier.block_connected(&Block { header: header_129, txdata: vec![revoked_local_txn[0].clone()] }, 129);
8110         check_closed_broadcast!(nodes[0], false);
8111         check_added_monitors!(nodes[0], 1);
8112         let penalty_txn = {
8113                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8114                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8115                 check_spends!(node_txn[0], revoked_local_txn[0]);
8116                 check_spends!(node_txn[1], revoked_local_txn[0]);
8117                 check_spends!(node_txn[2], revoked_local_txn[0]);
8118                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8119                 node_txn.clear();
8120                 penalty_txn
8121         };
8122         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8123         nodes[0].block_notifier.block_connected(&Block { header: header_130, txdata: penalty_txn }, 130);
8124         connect_blocks(&nodes[0].block_notifier, 5, 130,  false, header_130.block_hash());
8125         {
8126                 let monitors = nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap();
8127                 if let Some(monitor) = monitors.get(&OutPoint { txid: chan.3.txid(), index: 0 }) {
8128                         assert!(monitor.onchain_tx_handler.pending_claim_requests.is_empty());
8129                         assert!(monitor.onchain_tx_handler.claimable_outpoints.is_empty());
8130                 }
8131         }
8132 }
8133
8134 #[test]
8135 fn test_override_channel_config() {
8136         let chanmon_cfgs = create_chanmon_cfgs(2);
8137         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8138         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8139         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8140
8141         // Node0 initiates a channel to node1 using the override config.
8142         let mut override_config = UserConfig::default();
8143         override_config.own_channel_config.our_to_self_delay = 200;
8144
8145         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8146
8147         // Assert the channel created by node0 is using the override config.
8148         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8149         assert_eq!(res.channel_flags, 0);
8150         assert_eq!(res.to_self_delay, 200);
8151 }
8152
8153 #[test]
8154 fn test_override_0msat_htlc_minimum() {
8155         let mut zero_config = UserConfig::default();
8156         zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8157         let chanmon_cfgs = create_chanmon_cfgs(2);
8158         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8159         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8160         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8161
8162         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8163         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8164         assert_eq!(res.htlc_minimum_msat, 1);
8165
8166         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8167         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8168         assert_eq!(res.htlc_minimum_msat, 1);
8169 }
8170
8171 #[test]
8172 fn test_simple_payment_secret() {
8173         // Simple test of sending a payment with a payment_secret present. This does not use any AMP
8174         // features, however.
8175         let chanmon_cfgs = create_chanmon_cfgs(3);
8176         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8177         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8178         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8179
8180         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8181         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
8182         let logger = test_utils::TestLogger::new();
8183
8184         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8185         let payment_secret = PaymentSecret([0xdb; 32]);
8186         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8187         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();
8188         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2]]], 100000, payment_hash, Some(payment_secret.clone()));
8189         // Claiming with all the correct values but the wrong secret should result in nothing...
8190         assert_eq!(nodes[2].node.claim_funds(payment_preimage, &None, 100_000), false);
8191         assert_eq!(nodes[2].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 100_000), false);
8192         // ...but with the right secret we should be able to claim all the way back
8193         claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage, Some(payment_secret.clone()), 100_000);
8194 }
8195
8196 #[test]
8197 fn test_simple_mpp() {
8198         // Simple test of sending a multi-path payment.
8199         let chanmon_cfgs = create_chanmon_cfgs(4);
8200         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8201         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8202         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8203
8204         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8205         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8206         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8207         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
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 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();
8214         let path = route.paths[0].clone();
8215         route.paths.push(path);
8216         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8217         route.paths[0][0].short_channel_id = chan_1_id;
8218         route.paths[0][1].short_channel_id = chan_3_id;
8219         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8220         route.paths[1][0].short_channel_id = chan_2_id;
8221         route.paths[1][1].short_channel_id = chan_4_id;
8222         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, Some(payment_secret.clone()));
8223         // Claiming with all the correct values but the wrong secret should result in nothing...
8224         assert_eq!(nodes[3].node.claim_funds(payment_preimage, &None, 200_000), false);
8225         assert_eq!(nodes[3].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 200_000), false);
8226         // ...but with the right secret we should be able to claim all the way back
8227         claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage, Some(payment_secret), 200_000);
8228 }
8229
8230 #[test]
8231 fn test_update_err_monitor_lockdown() {
8232         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8233         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8234         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8235         //
8236         // This scenario may happen in a watchtower setup, where watchtower process a block height
8237         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8238         // commitment at same time.
8239
8240         let chanmon_cfgs = create_chanmon_cfgs(2);
8241         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8242         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8243         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8244
8245         // Create some initial channel
8246         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8247         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8248
8249         // Rebalance the network to generate htlc in the two directions
8250         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8251
8252         // Route a HTLC from node 0 to node 1 (but don't settle)
8253         let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8254
8255         // Copy SimpleManyChannelMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8256         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8257         let chain_monitor = chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet);
8258         let watchtower = {
8259                 let monitors = nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap();
8260                 let monitor = monitors.get(&outpoint).unwrap();
8261                 let mut w = test_utils::TestVecWriter(Vec::new());
8262                 monitor.write_for_disk(&mut w).unwrap();
8263                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
8264                                 &mut ::std::io::Cursor::new(&w.0)).unwrap().1;
8265                 assert!(new_monitor == *monitor);
8266                 let watchtower = test_utils::TestChannelMonitor::new(&chain_monitor, &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator);
8267                 assert!(watchtower.add_monitor(outpoint, new_monitor).is_ok());
8268                 watchtower
8269         };
8270         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8271         watchtower.simple_monitor.block_connected(&header, 200, &vec![], &vec![]);
8272
8273         // Try to update ChannelMonitor
8274         assert!(nodes[1].node.claim_funds(preimage, &None, 9_000_000));
8275         check_added_monitors!(nodes[1], 1);
8276         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8277         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8278         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8279         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8280                 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8281                         if let Err(_) =  watchtower.simple_monitor.update_monitor(outpoint, update.clone()) {} else { assert!(false); }
8282                         if let Ok(_) = nodes[0].chan_monitor.update_monitor(outpoint, update) {} else { assert!(false); }
8283                 } else { assert!(false); }
8284         } else { assert!(false); };
8285         // Our local monitor is in-sync and hasn't processed yet timeout
8286         check_added_monitors!(nodes[0], 1);
8287         let events = nodes[0].node.get_and_clear_pending_events();
8288         assert_eq!(events.len(), 1);
8289 }
8290
8291 #[test]
8292 fn test_concurrent_monitor_claim() {
8293         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8294         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8295         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8296         // state N+1 confirms. Alice claims output from state N+1.
8297
8298         let chanmon_cfgs = create_chanmon_cfgs(2);
8299         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8300         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8301         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8302
8303         // Create some initial channel
8304         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8305         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8306
8307         // Rebalance the network to generate htlc in the two directions
8308         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8309
8310         // Route a HTLC from node 0 to node 1 (but don't settle)
8311         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8312
8313         // Copy SimpleManyChannelMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8314         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8315         let chain_monitor = chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet);
8316         let watchtower_alice = {
8317                 let monitors = nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap();
8318                 let monitor = monitors.get(&outpoint).unwrap();
8319                 let mut w = test_utils::TestVecWriter(Vec::new());
8320                 monitor.write_for_disk(&mut w).unwrap();
8321                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
8322                                 &mut ::std::io::Cursor::new(&w.0)).unwrap().1;
8323                 assert!(new_monitor == *monitor);
8324                 let watchtower = test_utils::TestChannelMonitor::new(&chain_monitor, &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator);
8325                 assert!(watchtower.add_monitor(outpoint, new_monitor).is_ok());
8326                 watchtower
8327         };
8328         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8329         watchtower_alice.simple_monitor.block_connected(&header, 135, &vec![], &vec![]);
8330
8331         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8332         {
8333                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8334                 assert_eq!(txn.len(), 2);
8335                 txn.clear();
8336         }
8337
8338         // Copy SimpleManyChannelMonitor to simulate watchtower Bob and make it receive a commitment update first.
8339         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8340         let chain_monitor = chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet);
8341         let watchtower_bob = {
8342                 let monitors = nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap();
8343                 let monitor = monitors.get(&outpoint).unwrap();
8344                 let mut w = test_utils::TestVecWriter(Vec::new());
8345                 monitor.write_for_disk(&mut w).unwrap();
8346                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
8347                                 &mut ::std::io::Cursor::new(&w.0)).unwrap().1;
8348                 assert!(new_monitor == *monitor);
8349                 let watchtower = test_utils::TestChannelMonitor::new(&chain_monitor, &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator);
8350                 assert!(watchtower.add_monitor(outpoint, new_monitor).is_ok());
8351                 watchtower
8352         };
8353         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8354         watchtower_bob.simple_monitor.block_connected(&header, 134, &vec![], &vec![]);
8355
8356         // Route another payment to generate another update with still previous HTLC pending
8357         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
8358         {
8359                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
8360                 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();
8361                 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
8362         }
8363         check_added_monitors!(nodes[1], 1);
8364
8365         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8366         assert_eq!(updates.update_add_htlcs.len(), 1);
8367         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8368         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8369                 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8370                         // Watchtower Alice should already have seen the block and reject the update
8371                         if let Err(_) =  watchtower_alice.simple_monitor.update_monitor(outpoint, update.clone()) {} else { assert!(false); }
8372                         if let Ok(_) = watchtower_bob.simple_monitor.update_monitor(outpoint, update.clone()) {} else { assert!(false); }
8373                         if let Ok(_) = nodes[0].chan_monitor.update_monitor(outpoint, update) {} else { assert!(false); }
8374                 } else { assert!(false); }
8375         } else { assert!(false); };
8376         // Our local monitor is in-sync and hasn't processed yet timeout
8377         check_added_monitors!(nodes[0], 1);
8378
8379         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8380         watchtower_bob.simple_monitor.block_connected(&header, 135, &vec![], &vec![]);
8381
8382         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8383         let bob_state_y;
8384         {
8385                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8386                 assert_eq!(txn.len(), 2);
8387                 bob_state_y = txn[0].clone();
8388                 txn.clear();
8389         };
8390
8391         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8392         watchtower_alice.simple_monitor.block_connected(&header, 136, &vec![&bob_state_y][..], &vec![]);
8393         {
8394                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8395                 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8396                 // the onchain detection of the HTLC output
8397                 assert_eq!(htlc_txn.len(), 2);
8398                 check_spends!(htlc_txn[0], bob_state_y);
8399                 check_spends!(htlc_txn[1], bob_state_y);
8400         }
8401 }