Remove ChainWatchInterface from BlockNotifier
[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 block = Block {
424                 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
425                 txdata: vec![tx],
426         };
427         nodes[1].block_notifier.block_connected(&block, 1);
428         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()));
429
430         nodes[0].block_notifier.block_connected(&block, 1);
431         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
432         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
433
434         for node in nodes {
435                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
436                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
437                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
438         }
439 }
440
441 fn do_test_sanity_on_in_flight_opens(steps: u8) {
442         // Previously, we had issues deserializing channels when we hadn't connected the first block
443         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
444         // serialization round-trips and simply do steps towards opening a channel and then drop the
445         // Node objects.
446
447         let chanmon_cfgs = create_chanmon_cfgs(2);
448         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
449         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
450         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
451
452         if steps & 0b1000_0000 != 0{
453                 let block = Block {
454                         header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
455                         txdata: vec![],
456                 };
457                 nodes[0].block_notifier.block_connected(&block, 1);
458                 nodes[1].block_notifier.block_connected(&block, 1);
459         }
460
461         if steps & 0x0f == 0 { return; }
462         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
463         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
464
465         if steps & 0x0f == 1 { return; }
466         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
467         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
468
469         if steps & 0x0f == 2 { return; }
470         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
471
472         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
473
474         if steps & 0x0f == 3 { return; }
475         nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
476         check_added_monitors!(nodes[0], 0);
477         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
478
479         if steps & 0x0f == 4 { return; }
480         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
481         {
482                 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
483                 assert_eq!(added_monitors.len(), 1);
484                 assert_eq!(added_monitors[0].0, funding_output);
485                 added_monitors.clear();
486         }
487         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
488
489         if steps & 0x0f == 5 { return; }
490         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
491         {
492                 let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
493                 assert_eq!(added_monitors.len(), 1);
494                 assert_eq!(added_monitors[0].0, funding_output);
495                 added_monitors.clear();
496         }
497
498         let events_4 = nodes[0].node.get_and_clear_pending_events();
499         assert_eq!(events_4.len(), 1);
500         match events_4[0] {
501                 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
502                         assert_eq!(user_channel_id, 42);
503                         assert_eq!(*funding_txo, funding_output);
504                 },
505                 _ => panic!("Unexpected event"),
506         };
507
508         if steps & 0x0f == 6 { return; }
509         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx);
510
511         if steps & 0x0f == 7 { return; }
512         confirm_transaction(&nodes[0].block_notifier, &tx);
513         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
514 }
515
516 #[test]
517 fn test_sanity_on_in_flight_opens() {
518         do_test_sanity_on_in_flight_opens(0);
519         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
520         do_test_sanity_on_in_flight_opens(1);
521         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
522         do_test_sanity_on_in_flight_opens(2);
523         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
524         do_test_sanity_on_in_flight_opens(3);
525         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
526         do_test_sanity_on_in_flight_opens(4);
527         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
528         do_test_sanity_on_in_flight_opens(5);
529         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
530         do_test_sanity_on_in_flight_opens(6);
531         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
532         do_test_sanity_on_in_flight_opens(7);
533         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
534         do_test_sanity_on_in_flight_opens(8);
535         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
536 }
537
538 #[test]
539 fn test_update_fee_vanilla() {
540         let chanmon_cfgs = create_chanmon_cfgs(2);
541         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
542         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
543         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
544         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
545         let channel_id = chan.2;
546
547         let feerate = get_feerate!(nodes[0], channel_id);
548         nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
549         check_added_monitors!(nodes[0], 1);
550
551         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
552         assert_eq!(events_0.len(), 1);
553         let (update_msg, commitment_signed) = match events_0[0] {
554                         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 } } => {
555                         (update_fee.as_ref(), commitment_signed)
556                 },
557                 _ => panic!("Unexpected event"),
558         };
559         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
560
561         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
562         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
563         check_added_monitors!(nodes[1], 1);
564
565         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
566         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
567         check_added_monitors!(nodes[0], 1);
568
569         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
570         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
571         // No commitment_signed so get_event_msg's assert(len == 1) passes
572         check_added_monitors!(nodes[0], 1);
573
574         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
575         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
576         check_added_monitors!(nodes[1], 1);
577 }
578
579 #[test]
580 fn test_update_fee_that_funder_cannot_afford() {
581         let chanmon_cfgs = create_chanmon_cfgs(2);
582         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
583         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
584         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
585         let channel_value = 1888;
586         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000, InitFeatures::known(), InitFeatures::known());
587         let channel_id = chan.2;
588
589         let feerate = 260;
590         nodes[0].node.update_fee(channel_id, feerate).unwrap();
591         check_added_monitors!(nodes[0], 1);
592         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
593
594         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
595
596         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
597
598         //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
599         //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
600         {
601                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
602
603                 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
604                 let num_htlcs = commitment_tx.output.len() - 2;
605                 let total_fee: u64 = feerate as u64 * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
606                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
607                 actual_fee = channel_value - actual_fee;
608                 assert_eq!(total_fee, actual_fee);
609         }
610
611         //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
612         //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
613         nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
614         check_added_monitors!(nodes[0], 1);
615
616         let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
617
618         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap());
619
620         //While producing the commitment_signed response after handling a received update_fee request the
621         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
622         //Should produce and error.
623         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed);
624         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
625         check_added_monitors!(nodes[1], 1);
626         check_closed_broadcast!(nodes[1], true);
627 }
628
629 #[test]
630 fn test_update_fee_with_fundee_update_add_htlc() {
631         let chanmon_cfgs = create_chanmon_cfgs(2);
632         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
633         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
634         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
635         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
636         let channel_id = chan.2;
637         let logger = test_utils::TestLogger::new();
638
639         // balancing
640         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
641
642         let feerate = get_feerate!(nodes[0], channel_id);
643         nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
644         check_added_monitors!(nodes[0], 1);
645
646         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
647         assert_eq!(events_0.len(), 1);
648         let (update_msg, commitment_signed) = match events_0[0] {
649                         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 } } => {
650                         (update_fee.as_ref(), commitment_signed)
651                 },
652                 _ => panic!("Unexpected event"),
653         };
654         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
655         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
656         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
657         check_added_monitors!(nodes[1], 1);
658
659         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
660         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
661         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();
662
663         // nothing happens since node[1] is in AwaitingRemoteRevoke
664         nodes[1].node.send_payment(&route, our_payment_hash, &None).unwrap();
665         {
666                 let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
667                 assert_eq!(added_monitors.len(), 0);
668                 added_monitors.clear();
669         }
670         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
671         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
672         // node[1] has nothing to do
673
674         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
675         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
676         check_added_monitors!(nodes[0], 1);
677
678         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
679         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
680         // No commitment_signed so get_event_msg's assert(len == 1) passes
681         check_added_monitors!(nodes[0], 1);
682         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
683         check_added_monitors!(nodes[1], 1);
684         // AwaitingRemoteRevoke ends here
685
686         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
687         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
688         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
689         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
690         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
691         assert_eq!(commitment_update.update_fee.is_none(), true);
692
693         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
694         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
695         check_added_monitors!(nodes[0], 1);
696         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
697
698         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
699         check_added_monitors!(nodes[1], 1);
700         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
701
702         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
703         check_added_monitors!(nodes[1], 1);
704         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
705         // No commitment_signed so get_event_msg's assert(len == 1) passes
706
707         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
708         check_added_monitors!(nodes[0], 1);
709         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
710
711         expect_pending_htlcs_forwardable!(nodes[0]);
712
713         let events = nodes[0].node.get_and_clear_pending_events();
714         assert_eq!(events.len(), 1);
715         match events[0] {
716                 Event::PaymentReceived { .. } => { },
717                 _ => panic!("Unexpected event"),
718         };
719
720         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage, 800_000);
721
722         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000, 800_000);
723         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000, 800_000);
724         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
725 }
726
727 #[test]
728 fn test_update_fee() {
729         let chanmon_cfgs = create_chanmon_cfgs(2);
730         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
731         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
732         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
733         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
734         let channel_id = chan.2;
735
736         // A                                        B
737         // (1) update_fee/commitment_signed      ->
738         //                                       <- (2) revoke_and_ack
739         //                                       .- send (3) commitment_signed
740         // (4) update_fee/commitment_signed      ->
741         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
742         //                                       <- (3) commitment_signed delivered
743         // send (6) revoke_and_ack               -.
744         //                                       <- (5) deliver revoke_and_ack
745         // (6) deliver revoke_and_ack            ->
746         //                                       .- send (7) commitment_signed in response to (4)
747         //                                       <- (7) deliver commitment_signed
748         // revoke_and_ack                        ->
749
750         // Create and deliver (1)...
751         let feerate = get_feerate!(nodes[0], channel_id);
752         nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
753         check_added_monitors!(nodes[0], 1);
754
755         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
756         assert_eq!(events_0.len(), 1);
757         let (update_msg, commitment_signed) = match events_0[0] {
758                         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 } } => {
759                         (update_fee.as_ref(), commitment_signed)
760                 },
761                 _ => panic!("Unexpected event"),
762         };
763         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
764
765         // Generate (2) and (3):
766         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
767         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
768         check_added_monitors!(nodes[1], 1);
769
770         // Deliver (2):
771         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
772         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
773         check_added_monitors!(nodes[0], 1);
774
775         // Create and deliver (4)...
776         nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
777         check_added_monitors!(nodes[0], 1);
778         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
779         assert_eq!(events_0.len(), 1);
780         let (update_msg, commitment_signed) = match events_0[0] {
781                         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 } } => {
782                         (update_fee.as_ref(), commitment_signed)
783                 },
784                 _ => panic!("Unexpected event"),
785         };
786
787         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
788         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
789         check_added_monitors!(nodes[1], 1);
790         // ... creating (5)
791         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
792         // No commitment_signed so get_event_msg's assert(len == 1) passes
793
794         // Handle (3), creating (6):
795         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
796         check_added_monitors!(nodes[0], 1);
797         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
798         // No commitment_signed so get_event_msg's assert(len == 1) passes
799
800         // Deliver (5):
801         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
802         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
803         check_added_monitors!(nodes[0], 1);
804
805         // Deliver (6), creating (7):
806         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
807         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
808         assert!(commitment_update.update_add_htlcs.is_empty());
809         assert!(commitment_update.update_fulfill_htlcs.is_empty());
810         assert!(commitment_update.update_fail_htlcs.is_empty());
811         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
812         assert!(commitment_update.update_fee.is_none());
813         check_added_monitors!(nodes[1], 1);
814
815         // Deliver (7)
816         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
817         check_added_monitors!(nodes[0], 1);
818         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
819         // No commitment_signed so get_event_msg's assert(len == 1) passes
820
821         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
822         check_added_monitors!(nodes[1], 1);
823         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
824
825         assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
826         assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
827         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
828 }
829
830 #[test]
831 fn pre_funding_lock_shutdown_test() {
832         // Test sending a shutdown prior to funding_locked after funding generation
833         let chanmon_cfgs = create_chanmon_cfgs(2);
834         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
835         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
836         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
837         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0, InitFeatures::known(), InitFeatures::known());
838         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
839         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![tx.clone()]}, 1);
840         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![tx.clone()]}, 1);
841
842         nodes[0].node.close_channel(&OutPoint { txid: tx.txid(), index: 0 }.to_channel_id()).unwrap();
843         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
844         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
845         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
846         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
847
848         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
849         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
850         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
851         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
852         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
853         assert!(node_0_none.is_none());
854
855         assert!(nodes[0].node.list_channels().is_empty());
856         assert!(nodes[1].node.list_channels().is_empty());
857 }
858
859 #[test]
860 fn updates_shutdown_wait() {
861         // Test sending a shutdown with outstanding updates pending
862         let chanmon_cfgs = create_chanmon_cfgs(3);
863         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
864         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
865         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
866         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
867         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
868         let logger = test_utils::TestLogger::new();
869
870         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
871
872         nodes[0].node.close_channel(&chan_1.2).unwrap();
873         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
874         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
875         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
876         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
877
878         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
879         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
880
881         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
882
883         let net_graph_msg_handler0 = &nodes[0].net_graph_msg_handler;
884         let net_graph_msg_handler1 = &nodes[1].net_graph_msg_handler;
885         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();
886         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();
887         unwrap_send_err!(nodes[0].node.send_payment(&route_1, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
888         unwrap_send_err!(nodes[1].node.send_payment(&route_2, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
889
890         assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
891         check_added_monitors!(nodes[2], 1);
892         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
893         assert!(updates.update_add_htlcs.is_empty());
894         assert!(updates.update_fail_htlcs.is_empty());
895         assert!(updates.update_fail_malformed_htlcs.is_empty());
896         assert!(updates.update_fee.is_none());
897         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
898         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
899         check_added_monitors!(nodes[1], 1);
900         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
901         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
902
903         assert!(updates_2.update_add_htlcs.is_empty());
904         assert!(updates_2.update_fail_htlcs.is_empty());
905         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
906         assert!(updates_2.update_fee.is_none());
907         assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
908         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
909         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
910
911         let events = nodes[0].node.get_and_clear_pending_events();
912         assert_eq!(events.len(), 1);
913         match events[0] {
914                 Event::PaymentSent { ref payment_preimage } => {
915                         assert_eq!(our_payment_preimage, *payment_preimage);
916                 },
917                 _ => panic!("Unexpected event"),
918         }
919
920         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
921         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
922         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
923         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
924         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
925         assert!(node_0_none.is_none());
926
927         assert!(nodes[0].node.list_channels().is_empty());
928
929         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
930         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
931         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
932         assert!(nodes[1].node.list_channels().is_empty());
933         assert!(nodes[2].node.list_channels().is_empty());
934 }
935
936 #[test]
937 fn htlc_fail_async_shutdown() {
938         // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
939         let chanmon_cfgs = create_chanmon_cfgs(3);
940         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
941         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
942         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
943         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
944         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
945         let logger = test_utils::TestLogger::new();
946
947         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
948         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
949         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();
950         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
951         check_added_monitors!(nodes[0], 1);
952         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
953         assert_eq!(updates.update_add_htlcs.len(), 1);
954         assert!(updates.update_fulfill_htlcs.is_empty());
955         assert!(updates.update_fail_htlcs.is_empty());
956         assert!(updates.update_fail_malformed_htlcs.is_empty());
957         assert!(updates.update_fee.is_none());
958
959         nodes[1].node.close_channel(&chan_1.2).unwrap();
960         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
961         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
962         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
963
964         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
965         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
966         check_added_monitors!(nodes[1], 1);
967         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
968         commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
969
970         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
971         assert!(updates_2.update_add_htlcs.is_empty());
972         assert!(updates_2.update_fulfill_htlcs.is_empty());
973         assert_eq!(updates_2.update_fail_htlcs.len(), 1);
974         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
975         assert!(updates_2.update_fee.is_none());
976
977         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]);
978         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
979
980         expect_payment_failed!(nodes[0], our_payment_hash, false);
981
982         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
983         assert_eq!(msg_events.len(), 2);
984         let node_0_closing_signed = match msg_events[0] {
985                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
986                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
987                         (*msg).clone()
988                 },
989                 _ => panic!("Unexpected event"),
990         };
991         match msg_events[1] {
992                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
993                         assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
994                 },
995                 _ => panic!("Unexpected event"),
996         }
997
998         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
999         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
1000         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1001         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
1002         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1003         assert!(node_0_none.is_none());
1004
1005         assert!(nodes[0].node.list_channels().is_empty());
1006
1007         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1008         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1009         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1010         assert!(nodes[1].node.list_channels().is_empty());
1011         assert!(nodes[2].node.list_channels().is_empty());
1012 }
1013
1014 fn do_test_shutdown_rebroadcast(recv_count: u8) {
1015         // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
1016         // messages delivered prior to disconnect
1017         let chanmon_cfgs = create_chanmon_cfgs(3);
1018         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1019         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1020         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1021         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1022         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1023
1024         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
1025
1026         nodes[1].node.close_channel(&chan_1.2).unwrap();
1027         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1028         if recv_count > 0 {
1029                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
1030                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1031                 if recv_count > 1 {
1032                         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
1033                 }
1034         }
1035
1036         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1037         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1038
1039         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1040         let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1041         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1042         let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1043
1044         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish);
1045         let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1046         assert!(node_1_shutdown == node_1_2nd_shutdown);
1047
1048         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish);
1049         let node_0_2nd_shutdown = if recv_count > 0 {
1050                 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1051                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
1052                 node_0_2nd_shutdown
1053         } else {
1054                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1055                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
1056                 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
1057         };
1058         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown);
1059
1060         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1061         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1062
1063         assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
1064         check_added_monitors!(nodes[2], 1);
1065         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1066         assert!(updates.update_add_htlcs.is_empty());
1067         assert!(updates.update_fail_htlcs.is_empty());
1068         assert!(updates.update_fail_malformed_htlcs.is_empty());
1069         assert!(updates.update_fee.is_none());
1070         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
1071         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
1072         check_added_monitors!(nodes[1], 1);
1073         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1074         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
1075
1076         assert!(updates_2.update_add_htlcs.is_empty());
1077         assert!(updates_2.update_fail_htlcs.is_empty());
1078         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
1079         assert!(updates_2.update_fee.is_none());
1080         assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
1081         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
1082         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
1083
1084         let events = nodes[0].node.get_and_clear_pending_events();
1085         assert_eq!(events.len(), 1);
1086         match events[0] {
1087                 Event::PaymentSent { ref payment_preimage } => {
1088                         assert_eq!(our_payment_preimage, *payment_preimage);
1089                 },
1090                 _ => panic!("Unexpected event"),
1091         }
1092
1093         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1094         if recv_count > 0 {
1095                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
1096                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1097                 assert!(node_1_closing_signed.is_some());
1098         }
1099
1100         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1101         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1102
1103         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1104         let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1105         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1106         if recv_count == 0 {
1107                 // If all closing_signeds weren't delivered we can just resume where we left off...
1108                 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1109
1110                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish);
1111                 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1112                 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
1113
1114                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1115                 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1116                 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
1117
1118                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown);
1119                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1120
1121                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown);
1122                 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1123                 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
1124
1125                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed);
1126                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1127                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
1128                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1129                 assert!(node_0_none.is_none());
1130         } else {
1131                 // If one node, however, received + responded with an identical closing_signed we end
1132                 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
1133                 // There isn't really anything better we can do simply, but in the future we might
1134                 // explore storing a set of recently-closed channels that got disconnected during
1135                 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
1136                 // give our counterparty enough time to (potentially) broadcast a cooperative closing
1137                 // transaction.
1138                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1139
1140                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1141                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1142                 assert_eq!(msg_events.len(), 1);
1143                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
1144                         match action {
1145                                 &ErrorAction::SendErrorMessage { ref msg } => {
1146                                         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
1147                                         assert_eq!(msg.channel_id, chan_1.2);
1148                                 },
1149                                 _ => panic!("Unexpected event!"),
1150                         }
1151                 } else { panic!("Needed SendErrorMessage close"); }
1152
1153                 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
1154                 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
1155                 // closing_signed so we do it ourselves
1156                 check_closed_broadcast!(nodes[0], false);
1157                 check_added_monitors!(nodes[0], 1);
1158         }
1159
1160         assert!(nodes[0].node.list_channels().is_empty());
1161
1162         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1163         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1164         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1165         assert!(nodes[1].node.list_channels().is_empty());
1166         assert!(nodes[2].node.list_channels().is_empty());
1167 }
1168
1169 #[test]
1170 fn test_shutdown_rebroadcast() {
1171         do_test_shutdown_rebroadcast(0);
1172         do_test_shutdown_rebroadcast(1);
1173         do_test_shutdown_rebroadcast(2);
1174 }
1175
1176 #[test]
1177 fn fake_network_test() {
1178         // Simple test which builds a network of ChannelManagers, connects them to each other, and
1179         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
1180         let chanmon_cfgs = create_chanmon_cfgs(4);
1181         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1182         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1183         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1184
1185         // Create some initial channels
1186         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1187         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1188         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1189
1190         // Rebalance the network a bit by relaying one payment through all the channels...
1191         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1192         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1193         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1194         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1195
1196         // Send some more payments
1197         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000, 1_000_000);
1198         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000, 1_000_000);
1199         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000, 1_000_000);
1200
1201         // Test failure packets
1202         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1203         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1204
1205         // Add a new channel that skips 3
1206         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1207
1208         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000, 1_000_000);
1209         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000, 1_000_000);
1210         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1211         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1212         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1213         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1214         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1215
1216         // Do some rebalance loop payments, simultaneously
1217         let mut hops = Vec::with_capacity(3);
1218         hops.push(RouteHop {
1219                 pubkey: nodes[2].node.get_our_node_id(),
1220                 node_features: NodeFeatures::empty(),
1221                 short_channel_id: chan_2.0.contents.short_channel_id,
1222                 channel_features: ChannelFeatures::empty(),
1223                 fee_msat: 0,
1224                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1225         });
1226         hops.push(RouteHop {
1227                 pubkey: nodes[3].node.get_our_node_id(),
1228                 node_features: NodeFeatures::empty(),
1229                 short_channel_id: chan_3.0.contents.short_channel_id,
1230                 channel_features: ChannelFeatures::empty(),
1231                 fee_msat: 0,
1232                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1233         });
1234         hops.push(RouteHop {
1235                 pubkey: nodes[1].node.get_our_node_id(),
1236                 node_features: NodeFeatures::empty(),
1237                 short_channel_id: chan_4.0.contents.short_channel_id,
1238                 channel_features: ChannelFeatures::empty(),
1239                 fee_msat: 1000000,
1240                 cltv_expiry_delta: TEST_FINAL_CLTV,
1241         });
1242         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;
1243         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;
1244         let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1245
1246         let mut hops = Vec::with_capacity(3);
1247         hops.push(RouteHop {
1248                 pubkey: nodes[3].node.get_our_node_id(),
1249                 node_features: NodeFeatures::empty(),
1250                 short_channel_id: chan_4.0.contents.short_channel_id,
1251                 channel_features: ChannelFeatures::empty(),
1252                 fee_msat: 0,
1253                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1254         });
1255         hops.push(RouteHop {
1256                 pubkey: nodes[2].node.get_our_node_id(),
1257                 node_features: NodeFeatures::empty(),
1258                 short_channel_id: chan_3.0.contents.short_channel_id,
1259                 channel_features: ChannelFeatures::empty(),
1260                 fee_msat: 0,
1261                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1262         });
1263         hops.push(RouteHop {
1264                 pubkey: nodes[1].node.get_our_node_id(),
1265                 node_features: NodeFeatures::empty(),
1266                 short_channel_id: chan_2.0.contents.short_channel_id,
1267                 channel_features: ChannelFeatures::empty(),
1268                 fee_msat: 1000000,
1269                 cltv_expiry_delta: TEST_FINAL_CLTV,
1270         });
1271         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;
1272         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;
1273         let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1274
1275         // Claim the rebalances...
1276         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1277         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1, 1_000_000);
1278
1279         // Add a duplicate new channel from 2 to 4
1280         let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1281
1282         // Send some payments across both channels
1283         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1284         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1285         let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1286
1287
1288         route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1289         let events = nodes[0].node.get_and_clear_pending_msg_events();
1290         assert_eq!(events.len(), 0);
1291         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);
1292
1293         //TODO: Test that routes work again here as we've been notified that the channel is full
1294
1295         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3, 3_000_000);
1296         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4, 3_000_000);
1297         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5, 3_000_000);
1298
1299         // Close down the channels...
1300         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1301         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1302         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1303         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1304         close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1305 }
1306
1307 #[test]
1308 fn holding_cell_htlc_counting() {
1309         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1310         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1311         // commitment dance rounds.
1312         let chanmon_cfgs = create_chanmon_cfgs(3);
1313         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1314         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1315         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1316         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1317         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1318         let logger = test_utils::TestLogger::new();
1319
1320         let mut payments = Vec::new();
1321         for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1322                 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1323                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1324                 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();
1325                 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
1326                 payments.push((payment_preimage, payment_hash));
1327         }
1328         check_added_monitors!(nodes[1], 1);
1329
1330         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1331         assert_eq!(events.len(), 1);
1332         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1333         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1334
1335         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1336         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1337         // another HTLC.
1338         let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
1339         {
1340                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1341                 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();
1342                 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &None), true, APIError::ChannelUnavailable { ref err },
1343                         assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1344                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1345                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1346         }
1347
1348         // This should also be true if we try to forward a payment.
1349         let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
1350         {
1351                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1352                 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();
1353                 nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
1354                 check_added_monitors!(nodes[0], 1);
1355         }
1356
1357         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1358         assert_eq!(events.len(), 1);
1359         let payment_event = SendEvent::from_event(events.pop().unwrap());
1360         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1361
1362         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1363         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1364         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1365         // fails), the second will process the resulting failure and fail the HTLC backward.
1366         expect_pending_htlcs_forwardable!(nodes[1]);
1367         expect_pending_htlcs_forwardable!(nodes[1]);
1368         check_added_monitors!(nodes[1], 1);
1369
1370         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1371         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1372         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1373
1374         let events = nodes[0].node.get_and_clear_pending_msg_events();
1375         assert_eq!(events.len(), 1);
1376         match events[0] {
1377                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
1378                         assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
1379                 },
1380                 _ => panic!("Unexpected event"),
1381         }
1382
1383         expect_payment_failed!(nodes[0], payment_hash_2, false);
1384
1385         // Now forward all the pending HTLCs and claim them back
1386         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1387         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1388         check_added_monitors!(nodes[2], 1);
1389
1390         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1391         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1392         check_added_monitors!(nodes[1], 1);
1393         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1394
1395         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1396         check_added_monitors!(nodes[1], 1);
1397         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1398
1399         for ref update in as_updates.update_add_htlcs.iter() {
1400                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1401         }
1402         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1403         check_added_monitors!(nodes[2], 1);
1404         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1405         check_added_monitors!(nodes[2], 1);
1406         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1407
1408         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1409         check_added_monitors!(nodes[1], 1);
1410         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1411         check_added_monitors!(nodes[1], 1);
1412         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1413
1414         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1415         check_added_monitors!(nodes[2], 1);
1416
1417         expect_pending_htlcs_forwardable!(nodes[2]);
1418
1419         let events = nodes[2].node.get_and_clear_pending_events();
1420         assert_eq!(events.len(), payments.len());
1421         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1422                 match event {
1423                         &Event::PaymentReceived { ref payment_hash, .. } => {
1424                                 assert_eq!(*payment_hash, *hash);
1425                         },
1426                         _ => panic!("Unexpected event"),
1427                 };
1428         }
1429
1430         for (preimage, _) in payments.drain(..) {
1431                 claim_payment(&nodes[1], &[&nodes[2]], preimage, 100_000);
1432         }
1433
1434         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000, 1_000_000);
1435 }
1436
1437 #[test]
1438 fn duplicate_htlc_test() {
1439         // Test that we accept duplicate payment_hash HTLCs across the network and that
1440         // claiming/failing them are all separate and don't affect each other
1441         let chanmon_cfgs = create_chanmon_cfgs(6);
1442         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1443         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1444         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1445
1446         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1447         create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1448         create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1449         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1450         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1451         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1452
1453         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1454
1455         *nodes[0].network_payment_count.borrow_mut() -= 1;
1456         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1457
1458         *nodes[0].network_payment_count.borrow_mut() -= 1;
1459         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1460
1461         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage, 1_000_000);
1462         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1463         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage, 1_000_000);
1464 }
1465
1466 #[test]
1467 fn test_duplicate_htlc_different_direction_onchain() {
1468         // Test that ChannelMonitor doesn't generate 2 preimage txn
1469         // when we have 2 HTLCs with same preimage that go across a node
1470         // in opposite directions.
1471         let chanmon_cfgs = create_chanmon_cfgs(2);
1472         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1473         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1474         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1475
1476         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1477         let logger = test_utils::TestLogger::new();
1478
1479         // balancing
1480         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
1481
1482         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1483
1484         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1485         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();
1486         send_along_route_with_hash(&nodes[1], route, &vec!(&nodes[0])[..], 800_000, payment_hash);
1487
1488         // Provide preimage to node 0 by claiming payment
1489         nodes[0].node.claim_funds(payment_preimage, &None, 800_000);
1490         check_added_monitors!(nodes[0], 1);
1491
1492         // Broadcast node 1 commitment txn
1493         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1494
1495         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1496         let mut has_both_htlcs = 0; // check htlcs match ones committed
1497         for outp in remote_txn[0].output.iter() {
1498                 if outp.value == 800_000 / 1000 {
1499                         has_both_htlcs += 1;
1500                 } else if outp.value == 900_000 / 1000 {
1501                         has_both_htlcs += 1;
1502                 }
1503         }
1504         assert_eq!(has_both_htlcs, 2);
1505
1506         let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1507         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
1508         check_added_monitors!(nodes[0], 1);
1509
1510         // Check we only broadcast 1 timeout tx
1511         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1512         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()) };
1513         assert_eq!(claim_txn.len(), 5);
1514         check_spends!(claim_txn[2], chan_1.3);
1515         check_spends!(claim_txn[3], claim_txn[2]);
1516         assert_eq!(htlc_pair.0.input.len(), 1);
1517         assert_eq!(htlc_pair.0.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1518         check_spends!(htlc_pair.0, remote_txn[0]);
1519         assert_eq!(htlc_pair.1.input.len(), 1);
1520         assert_eq!(htlc_pair.1.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1521         check_spends!(htlc_pair.1, remote_txn[0]);
1522
1523         let events = nodes[0].node.get_and_clear_pending_msg_events();
1524         assert_eq!(events.len(), 2);
1525         for e in events {
1526                 match e {
1527                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1528                         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, .. } } => {
1529                                 assert!(update_add_htlcs.is_empty());
1530                                 assert!(update_fail_htlcs.is_empty());
1531                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1532                                 assert!(update_fail_malformed_htlcs.is_empty());
1533                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1534                         },
1535                         _ => panic!("Unexpected event"),
1536                 }
1537         }
1538 }
1539
1540 #[test]
1541 fn test_basic_channel_reserve() {
1542         let chanmon_cfgs = create_chanmon_cfgs(2);
1543         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1544         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1545         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1546         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1547         let logger = test_utils::TestLogger::new();
1548
1549         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1550         let channel_reserve = chan_stat.channel_reserve_msat;
1551
1552         // The 2* and +1 are for the fee spike reserve.
1553         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
1554         let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1);
1555         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1556         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1557         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();
1558         let err = nodes[0].node.send_payment(&route, our_payment_hash, &None).err().unwrap();
1559         match err {
1560                 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1561                         match &fails[0] {
1562                                 &APIError::ChannelUnavailable{ref err} =>
1563                                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1564                                 _ => panic!("Unexpected error variant"),
1565                         }
1566                 },
1567                 _ => panic!("Unexpected error variant"),
1568         }
1569         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1570         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);
1571
1572         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send, max_can_send);
1573 }
1574
1575 #[test]
1576 fn test_fee_spike_violation_fails_htlc() {
1577         let chanmon_cfgs = create_chanmon_cfgs(2);
1578         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1579         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1580         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1581         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1582         let logger = test_utils::TestLogger::new();
1583
1584         macro_rules! get_route_and_payment_hash {
1585                 ($recv_value: expr) => {{
1586                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1587                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler.network_graph.read().unwrap();
1588                         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();
1589                         (route, payment_hash, payment_preimage)
1590                 }}
1591         };
1592
1593         let (route, payment_hash, _) = get_route_and_payment_hash!(3460001);
1594         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1595         let secp_ctx = Secp256k1::new();
1596         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1597
1598         let cur_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1599
1600         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1601         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &None, cur_height).unwrap();
1602         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1603         let msg = msgs::UpdateAddHTLC {
1604                 channel_id: chan.2,
1605                 htlc_id: 0,
1606                 amount_msat: htlc_msat,
1607                 payment_hash: payment_hash,
1608                 cltv_expiry: htlc_cltv,
1609                 onion_routing_packet: onion_packet,
1610         };
1611
1612         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1613
1614         // Now manually create the commitment_signed message corresponding to the update_add
1615         // nodes[0] just sent. In the code for construction of this message, "local" refers
1616         // to the sender of the message, and "remote" refers to the receiver.
1617
1618         let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1619
1620         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1621
1622         // Get the EnforcingChannelKeys for each channel, which will be used to (1) get the keys
1623         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1624         let (local_revocation_basepoint, local_htlc_basepoint, local_payment_point, local_secret, local_secret2) = {
1625                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1626                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1627                 let chan_keys = local_chan.get_keys();
1628                 let pubkeys = chan_keys.pubkeys();
1629                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint, pubkeys.payment_point,
1630                  chan_keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER), chan_keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2))
1631         };
1632         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_payment_point, remote_secret1) = {
1633                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1634                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1635                 let chan_keys = remote_chan.get_keys();
1636                 let pubkeys = chan_keys.pubkeys();
1637                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint, pubkeys.payment_point,
1638                  chan_keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1))
1639         };
1640
1641         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1642         let commitment_secret = SecretKey::from_slice(&remote_secret1).unwrap();
1643         let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &commitment_secret);
1644         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &per_commitment_point, &remote_delayed_payment_basepoint,
1645                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1646
1647         // Build the remote commitment transaction so we can sign it, and then later use the
1648         // signature for the commitment_signed message.
1649         let local_chan_balance = 1313;
1650         let static_payment_pk = local_payment_point.serialize();
1651         let remote_commit_tx_output = TxOut {
1652                                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0)
1653                                                              .push_slice(&WPubkeyHash::hash(&static_payment_pk)[..])
1654                                                              .into_script(),
1655                 value: local_chan_balance as u64
1656         };
1657
1658         let local_commit_tx_output = TxOut {
1659                 script_pubkey: chan_utils::get_revokeable_redeemscript(&commit_tx_keys.revocation_key,
1660                                                                                BREAKDOWN_TIMEOUT,
1661                                                                                &commit_tx_keys.broadcaster_delayed_payment_key).to_v0_p2wsh(),
1662                                 value: 95000,
1663         };
1664
1665         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1666                 offered: false,
1667                 amount_msat: 3460001,
1668                 cltv_expiry: htlc_cltv,
1669                 payment_hash: payment_hash,
1670                 transaction_output_index: Some(1),
1671         };
1672
1673         let htlc_output = TxOut {
1674                 script_pubkey: chan_utils::get_htlc_redeemscript(&accepted_htlc_info, &commit_tx_keys).to_v0_p2wsh(),
1675                 value: 3460001 / 1000
1676         };
1677
1678         let commit_tx_obscure_factor = {
1679                 let mut sha = Sha256::engine();
1680                 let remote_payment_point = &remote_payment_point.serialize();
1681                 sha.input(&local_payment_point.serialize());
1682                 sha.input(remote_payment_point);
1683                 let res = Sha256::from_engine(sha).into_inner();
1684
1685                 ((res[26] as u64) << 5*8) |
1686                 ((res[27] as u64) << 4*8) |
1687                 ((res[28] as u64) << 3*8) |
1688                 ((res[29] as u64) << 2*8) |
1689                 ((res[30] as u64) << 1*8) |
1690                 ((res[31] as u64) << 0*8)
1691         };
1692         let commitment_number = 1;
1693         let obscured_commitment_transaction_number = commit_tx_obscure_factor ^ commitment_number;
1694         let lock_time = ((0x20 as u32) << 8*3) | ((obscured_commitment_transaction_number & 0xffffffu64) as u32);
1695         let input = TxIn {
1696                 previous_output: BitcoinOutPoint { txid: chan.3.txid(), vout: 0 },
1697                 script_sig: Script::new(),
1698                 sequence: ((0x80 as u32) << 8*3) | ((obscured_commitment_transaction_number >> 3*8) as u32),
1699                 witness: Vec::new(),
1700         };
1701
1702         let commit_tx = Transaction {
1703                 version: 2,
1704                 lock_time,
1705                 input: vec![input],
1706                 output: vec![remote_commit_tx_output, htlc_output, local_commit_tx_output],
1707         };
1708         let res = {
1709                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1710                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1711                 let local_chan_keys = local_chan.get_keys();
1712                 let pre_commit_tx_keys = PreCalculatedTxCreationKeys::new(commit_tx_keys);
1713                 local_chan_keys.sign_counterparty_commitment(feerate_per_kw, &commit_tx, &pre_commit_tx_keys, &[&accepted_htlc_info], &secp_ctx).unwrap()
1714         };
1715
1716         let commit_signed_msg = msgs::CommitmentSigned {
1717                 channel_id: chan.2,
1718                 signature: res.0,
1719                 htlc_signatures: res.1
1720         };
1721
1722         // Send the commitment_signed message to the nodes[1].
1723         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1724         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1725
1726         // Send the RAA to nodes[1].
1727         let per_commitment_secret = local_secret;
1728         let next_secret = SecretKey::from_slice(&local_secret2).unwrap();
1729         let next_per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &next_secret);
1730         let raa_msg = msgs::RevokeAndACK{ channel_id: chan.2, per_commitment_secret, next_per_commitment_point};
1731         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1732
1733         let events = nodes[1].node.get_and_clear_pending_msg_events();
1734         assert_eq!(events.len(), 1);
1735         // Make sure the HTLC failed in the way we expect.
1736         match events[0] {
1737                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1738                         assert_eq!(update_fail_htlcs.len(), 1);
1739                         update_fail_htlcs[0].clone()
1740                 },
1741                 _ => panic!("Unexpected event"),
1742         };
1743         nodes[1].logger.assert_log("lightning::ln::channel".to_string(), "Attempting to fail HTLC due to fee spike buffer violation".to_string(), 1);
1744
1745         check_added_monitors!(nodes[1], 2);
1746 }
1747
1748 #[test]
1749 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1750         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1751         // Set the fee rate for the channel very high, to the point where the fundee
1752         // sending any amount would result in a channel reserve violation. In this test
1753         // we check that we would be prevented from sending an HTLC in this situation.
1754         chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1755         chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1756         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1757         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1758         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1759         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1760         let logger = test_utils::TestLogger::new();
1761
1762         macro_rules! get_route_and_payment_hash {
1763                 ($recv_value: expr) => {{
1764                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1765                         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1766                         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();
1767                         (route, payment_hash, payment_preimage)
1768                 }}
1769         };
1770
1771         let (route, our_payment_hash, _) = get_route_and_payment_hash!(1000);
1772         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1773                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1774         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1775         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);
1776 }
1777
1778 #[test]
1779 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1780         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1781         // Set the fee rate for the channel very high, to the point where the funder
1782         // receiving 1 update_add_htlc would result in them closing the channel due
1783         // to channel reserve violation. This close could also happen if the fee went
1784         // up a more realistic amount, but many HTLCs were outstanding at the time of
1785         // the update_add_htlc.
1786         chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1787         chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1788         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1789         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1790         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1791         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1792         let logger = test_utils::TestLogger::new();
1793
1794         macro_rules! get_route_and_payment_hash {
1795                 ($recv_value: expr) => {{
1796                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1797                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1798                         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();
1799                         (route, payment_hash, payment_preimage)
1800                 }}
1801         };
1802
1803         let (route, payment_hash, _) = get_route_and_payment_hash!(1000);
1804         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1805         let secp_ctx = Secp256k1::new();
1806         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1807         let cur_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1808         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1809         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 1000, &None, cur_height).unwrap();
1810         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1811         let msg = msgs::UpdateAddHTLC {
1812                 channel_id: chan.2,
1813                 htlc_id: 1,
1814                 amount_msat: htlc_msat + 1,
1815                 payment_hash: payment_hash,
1816                 cltv_expiry: htlc_cltv,
1817                 onion_routing_packet: onion_packet,
1818         };
1819
1820         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1821         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1822         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);
1823         assert_eq!(nodes[0].node.list_channels().len(), 0);
1824         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1825         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1826         check_added_monitors!(nodes[0], 1);
1827 }
1828
1829 #[test]
1830 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1831         let chanmon_cfgs = create_chanmon_cfgs(3);
1832         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1833         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1834         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1835         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1836         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1837         let logger = test_utils::TestLogger::new();
1838
1839         macro_rules! get_route_and_payment_hash {
1840                 ($recv_value: expr) => {{
1841                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1842                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1843                         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();
1844                         (route, payment_hash, payment_preimage)
1845                 }}
1846         };
1847
1848         let feemsat = 239;
1849         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1850         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1851         let feerate = get_feerate!(nodes[0], chan.2);
1852
1853         // Add a 2* and +1 for the fee spike reserve.
1854         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1);
1855         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;
1856         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1857
1858         // Add a pending HTLC.
1859         let (route_1, our_payment_hash_1, _) = get_route_and_payment_hash!(amt_msat_1);
1860         let payment_event_1 = {
1861                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
1862                 check_added_monitors!(nodes[0], 1);
1863
1864                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1865                 assert_eq!(events.len(), 1);
1866                 SendEvent::from_event(events.remove(0))
1867         };
1868         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1869
1870         // Attempt to trigger a channel reserve violation --> payment failure.
1871         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2);
1872         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;
1873         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1874         let (route_2, _, _) = get_route_and_payment_hash!(amt_msat_2);
1875
1876         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1877         let secp_ctx = Secp256k1::new();
1878         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1879         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1880         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1881         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height).unwrap();
1882         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1883         let msg = msgs::UpdateAddHTLC {
1884                 channel_id: chan.2,
1885                 htlc_id: 1,
1886                 amount_msat: htlc_msat + 1,
1887                 payment_hash: our_payment_hash_1,
1888                 cltv_expiry: htlc_cltv,
1889                 onion_routing_packet: onion_packet,
1890         };
1891
1892         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1893         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1894         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1895         assert_eq!(nodes[1].node.list_channels().len(), 1);
1896         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1897         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1898         check_added_monitors!(nodes[1], 1);
1899 }
1900
1901 #[test]
1902 fn test_inbound_outbound_capacity_is_not_zero() {
1903         let chanmon_cfgs = create_chanmon_cfgs(2);
1904         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1905         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1906         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1907         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1908         let channels0 = node_chanmgrs[0].list_channels();
1909         let channels1 = node_chanmgrs[1].list_channels();
1910         assert_eq!(channels0.len(), 1);
1911         assert_eq!(channels1.len(), 1);
1912
1913         assert_eq!(channels0[0].inbound_capacity_msat, 95000000);
1914         assert_eq!(channels1[0].outbound_capacity_msat, 95000000);
1915
1916         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000);
1917         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000);
1918 }
1919
1920 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64) -> u64 {
1921         (COMMITMENT_TX_BASE_WEIGHT + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1922 }
1923
1924 #[test]
1925 fn test_channel_reserve_holding_cell_htlcs() {
1926         let chanmon_cfgs = create_chanmon_cfgs(3);
1927         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1928         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1929         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1930         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1931         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1932         let logger = test_utils::TestLogger::new();
1933
1934         let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1935         let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1936
1937         let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1938         let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1939
1940         macro_rules! get_route_and_payment_hash {
1941                 ($recv_value: expr) => {{
1942                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1943                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1944                         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();
1945                         (route, payment_hash, payment_preimage)
1946                 }}
1947         };
1948
1949         macro_rules! expect_forward {
1950                 ($node: expr) => {{
1951                         let mut events = $node.node.get_and_clear_pending_msg_events();
1952                         assert_eq!(events.len(), 1);
1953                         check_added_monitors!($node, 1);
1954                         let payment_event = SendEvent::from_event(events.remove(0));
1955                         payment_event
1956                 }}
1957         }
1958
1959         let feemsat = 239; // somehow we know?
1960         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1961         let feerate = get_feerate!(nodes[0], chan_1.2);
1962
1963         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1964
1965         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1966         {
1967                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
1968                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1969                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1970                         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)));
1971                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1972                 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);
1973         }
1974
1975         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1976         // nodes[0]'s wealth
1977         loop {
1978                 let amt_msat = recv_value_0 + total_fee_msat;
1979                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1980                 // Also, ensure that each payment has enough to be over the dust limit to
1981                 // ensure it'll be included in each commit tx fee calculation.
1982                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1983                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1984                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1985                         break;
1986                 }
1987                 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0, recv_value_0);
1988
1989                 let (stat01_, stat11_, stat12_, stat22_) = (
1990                         get_channel_value_stat!(nodes[0], chan_1.2),
1991                         get_channel_value_stat!(nodes[1], chan_1.2),
1992                         get_channel_value_stat!(nodes[1], chan_2.2),
1993                         get_channel_value_stat!(nodes[2], chan_2.2),
1994                 );
1995
1996                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1997                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1998                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1999                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
2000                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
2001         }
2002
2003         // adding pending output.
2004         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
2005         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
2006         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
2007         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
2008         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
2009         // cases where 1 msat over X amount will cause a payment failure, but anything less than
2010         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
2011         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
2012         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
2013         // policy.
2014         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1);
2015         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
2016         let amt_msat_1 = recv_value_1 + total_fee_msat;
2017
2018         let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
2019         let payment_event_1 = {
2020                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
2021                 check_added_monitors!(nodes[0], 1);
2022
2023                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2024                 assert_eq!(events.len(), 1);
2025                 SendEvent::from_event(events.remove(0))
2026         };
2027         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
2028
2029         // channel reserve test with htlc pending output > 0
2030         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
2031         {
2032                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
2033                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
2034                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
2035                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2036         }
2037
2038         // split the rest to test holding cell
2039         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
2040         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
2041         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
2042         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
2043         {
2044                 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
2045                 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);
2046         }
2047
2048         // now see if they go through on both sides
2049         let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
2050         // but this will stuck in the holding cell
2051         nodes[0].node.send_payment(&route_21, our_payment_hash_21, &None).unwrap();
2052         check_added_monitors!(nodes[0], 0);
2053         let events = nodes[0].node.get_and_clear_pending_events();
2054         assert_eq!(events.len(), 0);
2055
2056         // test with outbound holding cell amount > 0
2057         {
2058                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
2059                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
2060                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
2061                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2062                 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);
2063         }
2064
2065         let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
2066         // this will also stuck in the holding cell
2067         nodes[0].node.send_payment(&route_22, our_payment_hash_22, &None).unwrap();
2068         check_added_monitors!(nodes[0], 0);
2069         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
2070         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2071
2072         // flush the pending htlc
2073         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
2074         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2075         check_added_monitors!(nodes[1], 1);
2076
2077         // the pending htlc should be promoted to committed
2078         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
2079         check_added_monitors!(nodes[0], 1);
2080         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2081
2082         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
2083         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2084         // No commitment_signed so get_event_msg's assert(len == 1) passes
2085         check_added_monitors!(nodes[0], 1);
2086
2087         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
2088         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2089         check_added_monitors!(nodes[1], 1);
2090
2091         expect_pending_htlcs_forwardable!(nodes[1]);
2092
2093         let ref payment_event_11 = expect_forward!(nodes[1]);
2094         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
2095         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
2096
2097         expect_pending_htlcs_forwardable!(nodes[2]);
2098         expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
2099
2100         // flush the htlcs in the holding cell
2101         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
2102         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
2103         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
2104         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
2105         expect_pending_htlcs_forwardable!(nodes[1]);
2106
2107         let ref payment_event_3 = expect_forward!(nodes[1]);
2108         assert_eq!(payment_event_3.msgs.len(), 2);
2109         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
2110         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
2111
2112         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2113         expect_pending_htlcs_forwardable!(nodes[2]);
2114
2115         let events = nodes[2].node.get_and_clear_pending_events();
2116         assert_eq!(events.len(), 2);
2117         match events[0] {
2118                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2119                         assert_eq!(our_payment_hash_21, *payment_hash);
2120                         assert_eq!(*payment_secret, None);
2121                         assert_eq!(recv_value_21, amt);
2122                 },
2123                 _ => panic!("Unexpected event"),
2124         }
2125         match events[1] {
2126                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2127                         assert_eq!(our_payment_hash_22, *payment_hash);
2128                         assert_eq!(None, *payment_secret);
2129                         assert_eq!(recv_value_22, amt);
2130                 },
2131                 _ => panic!("Unexpected event"),
2132         }
2133
2134         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1, recv_value_1);
2135         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21, recv_value_21);
2136         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22, recv_value_22);
2137
2138         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1);
2139         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2140         {
2141                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_3 + 1);
2142                 let err = nodes[0].node.send_payment(&route, our_payment_hash, &None).err().unwrap();
2143                 match err {
2144                         PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
2145                                 match &fails[0] {
2146                                         &APIError::ChannelUnavailable{ref err} =>
2147                                                 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
2148                                         _ => panic!("Unexpected error variant"),
2149                                 }
2150                         },
2151                         _ => panic!("Unexpected error variant"),
2152                 }
2153                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2154                 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);
2155         }
2156
2157         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3, recv_value_3);
2158
2159         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1);
2160         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);
2161         let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2162         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2163         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2164
2165         let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2166         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2167 }
2168
2169 #[test]
2170 fn channel_reserve_in_flight_removes() {
2171         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2172         // can send to its counterparty, but due to update ordering, the other side may not yet have
2173         // considered those HTLCs fully removed.
2174         // This tests that we don't count HTLCs which will not be included in the next remote
2175         // commitment transaction towards the reserve value (as it implies no commitment transaction
2176         // will be generated which violates the remote reserve value).
2177         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2178         // To test this we:
2179         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2180         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2181         //    you only consider the value of the first HTLC, it may not),
2182         //  * start routing a third HTLC from A to B,
2183         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2184         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2185         //  * deliver the first fulfill from B
2186         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2187         //    claim,
2188         //  * deliver A's response CS and RAA.
2189         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2190         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2191         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2192         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2193         let chanmon_cfgs = create_chanmon_cfgs(2);
2194         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2195         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2196         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2197         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2198         let logger = test_utils::TestLogger::new();
2199
2200         let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2201         // Route the first two HTLCs.
2202         let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
2203         let (payment_preimage_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
2204
2205         // Start routing the third HTLC (this is just used to get everyone in the right state).
2206         let (payment_preimage_3, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
2207         let send_1 = {
2208                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
2209                 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();
2210                 nodes[0].node.send_payment(&route, payment_hash_3, &None).unwrap();
2211                 check_added_monitors!(nodes[0], 1);
2212                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2213                 assert_eq!(events.len(), 1);
2214                 SendEvent::from_event(events.remove(0))
2215         };
2216
2217         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2218         // initial fulfill/CS.
2219         assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000));
2220         check_added_monitors!(nodes[1], 1);
2221         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2222
2223         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2224         // remove the second HTLC when we send the HTLC back from B to A.
2225         assert!(nodes[1].node.claim_funds(payment_preimage_2, &None, 20000));
2226         check_added_monitors!(nodes[1], 1);
2227         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2228
2229         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2230         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2231         check_added_monitors!(nodes[0], 1);
2232         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2233         expect_payment_sent!(nodes[0], payment_preimage_1);
2234
2235         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2236         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2237         check_added_monitors!(nodes[1], 1);
2238         // B is already AwaitingRAA, so cant generate a CS here
2239         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2240
2241         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2242         check_added_monitors!(nodes[1], 1);
2243         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2244
2245         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2246         check_added_monitors!(nodes[0], 1);
2247         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2248
2249         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2250         check_added_monitors!(nodes[1], 1);
2251         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2252
2253         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2254         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2255         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2256         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2257         // on-chain as necessary).
2258         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2259         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2260         check_added_monitors!(nodes[0], 1);
2261         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2262         expect_payment_sent!(nodes[0], payment_preimage_2);
2263
2264         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2265         check_added_monitors!(nodes[1], 1);
2266         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2267
2268         expect_pending_htlcs_forwardable!(nodes[1]);
2269         expect_payment_received!(nodes[1], payment_hash_3, 100000);
2270
2271         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2272         // resolve the second HTLC from A's point of view.
2273         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2274         check_added_monitors!(nodes[0], 1);
2275         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2276
2277         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2278         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2279         let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[1]);
2280         let send_2 = {
2281                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
2282                 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();
2283                 nodes[1].node.send_payment(&route, payment_hash_4, &None).unwrap();
2284                 check_added_monitors!(nodes[1], 1);
2285                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2286                 assert_eq!(events.len(), 1);
2287                 SendEvent::from_event(events.remove(0))
2288         };
2289
2290         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2291         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2292         check_added_monitors!(nodes[0], 1);
2293         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2294
2295         // Now just resolve all the outstanding messages/HTLCs for completeness...
2296
2297         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2298         check_added_monitors!(nodes[1], 1);
2299         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2300
2301         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2302         check_added_monitors!(nodes[1], 1);
2303
2304         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2305         check_added_monitors!(nodes[0], 1);
2306         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2307
2308         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2309         check_added_monitors!(nodes[1], 1);
2310         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2311
2312         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2313         check_added_monitors!(nodes[0], 1);
2314
2315         expect_pending_htlcs_forwardable!(nodes[0]);
2316         expect_payment_received!(nodes[0], payment_hash_4, 10000);
2317
2318         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4, 10_000);
2319         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3, 100_000);
2320 }
2321
2322 #[test]
2323 fn channel_monitor_network_test() {
2324         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2325         // tests that ChannelMonitor is able to recover from various states.
2326         let chanmon_cfgs = create_chanmon_cfgs(5);
2327         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2328         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2329         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2330
2331         // Create some initial channels
2332         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2333         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2334         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2335         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2336
2337         // Rebalance the network a bit by relaying one payment through all the channels...
2338         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2339         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2340         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2341         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2342
2343         // Simple case with no pending HTLCs:
2344         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2345         check_added_monitors!(nodes[1], 1);
2346         {
2347                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2348                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2349                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
2350                 check_added_monitors!(nodes[0], 1);
2351                 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2352         }
2353         get_announce_close_broadcast_events(&nodes, 0, 1);
2354         assert_eq!(nodes[0].node.list_channels().len(), 0);
2355         assert_eq!(nodes[1].node.list_channels().len(), 1);
2356
2357         // One pending HTLC is discarded by the force-close:
2358         let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2359
2360         // Simple case of one pending HTLC to HTLC-Timeout
2361         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2362         check_added_monitors!(nodes[1], 1);
2363         {
2364                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2365                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2366                 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
2367                 check_added_monitors!(nodes[2], 1);
2368                 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2369         }
2370         get_announce_close_broadcast_events(&nodes, 1, 2);
2371         assert_eq!(nodes[1].node.list_channels().len(), 0);
2372         assert_eq!(nodes[2].node.list_channels().len(), 1);
2373
2374         macro_rules! claim_funds {
2375                 ($node: expr, $prev_node: expr, $preimage: expr, $amount: expr) => {
2376                         {
2377                                 assert!($node.node.claim_funds($preimage, &None, $amount));
2378                                 check_added_monitors!($node, 1);
2379
2380                                 let events = $node.node.get_and_clear_pending_msg_events();
2381                                 assert_eq!(events.len(), 1);
2382                                 match events[0] {
2383                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2384                                                 assert!(update_add_htlcs.is_empty());
2385                                                 assert!(update_fail_htlcs.is_empty());
2386                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2387                                         },
2388                                         _ => panic!("Unexpected event"),
2389                                 };
2390                         }
2391                 }
2392         }
2393
2394         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2395         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2396         nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2397         check_added_monitors!(nodes[2], 1);
2398         let node2_commitment_txid;
2399         {
2400                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2401                 node2_commitment_txid = node_txn[0].txid();
2402
2403                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2404                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, 3_000_000);
2405
2406                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2407                 nodes[3].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
2408                 check_added_monitors!(nodes[3], 1);
2409
2410                 check_preimage_claim(&nodes[3], &node_txn);
2411         }
2412         get_announce_close_broadcast_events(&nodes, 2, 3);
2413         assert_eq!(nodes[2].node.list_channels().len(), 0);
2414         assert_eq!(nodes[3].node.list_channels().len(), 1);
2415
2416         { // Cheat and reset nodes[4]'s height to 1
2417                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2418                 nodes[4].block_notifier.block_connected(&Block { header, txdata: vec![] }, 1);
2419         }
2420
2421         assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
2422         assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
2423         // One pending HTLC to time out:
2424         let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2425         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2426         // buffer space).
2427
2428         let (close_chan_update_1, close_chan_update_2) = {
2429                 let mut block = Block {
2430                         header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2431                         txdata: vec![],
2432                 };
2433                 nodes[3].block_notifier.block_connected(&block, 2);
2434                 for i in 3..TEST_FINAL_CLTV + 2 + LATENCY_GRACE_PERIOD_BLOCKS + 1 {
2435                         block = Block {
2436                                 header: BlockHeader { version: 0x20000000, prev_blockhash: block.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2437                                 txdata: vec![],
2438                         };
2439                         nodes[3].block_notifier.block_connected(&block, i);
2440                 }
2441                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2442                 assert_eq!(events.len(), 1);
2443                 let close_chan_update_1 = match events[0] {
2444                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2445                                 msg.clone()
2446                         },
2447                         _ => panic!("Unexpected event"),
2448                 };
2449                 check_added_monitors!(nodes[3], 1);
2450
2451                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2452                 {
2453                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2454                         node_txn.retain(|tx| {
2455                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2456                                         false
2457                                 } else { true }
2458                         });
2459                 }
2460
2461                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2462
2463                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2464                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, 3_000_000);
2465
2466                 block = Block {
2467                         header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2468                         txdata: vec![],
2469                 };
2470
2471                 nodes[4].block_notifier.block_connected(&block, 2);
2472                 for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
2473                         block = Block {
2474                                 header: BlockHeader { version: 0x20000000, prev_blockhash: block.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2475                                 txdata: vec![],
2476                         };
2477                         nodes[4].block_notifier.block_connected(&block, i);
2478                 }
2479                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2480                 assert_eq!(events.len(), 1);
2481                 let close_chan_update_2 = match events[0] {
2482                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2483                                 msg.clone()
2484                         },
2485                         _ => panic!("Unexpected event"),
2486                 };
2487                 check_added_monitors!(nodes[4], 1);
2488                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2489
2490                 block = Block {
2491                         header: BlockHeader { version: 0x20000000, prev_blockhash: block.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2492                         txdata: vec![node_txn[0].clone()],
2493                 };
2494                 nodes[4].block_notifier.block_connected(&block, TEST_FINAL_CLTV - 5);
2495
2496                 check_preimage_claim(&nodes[4], &node_txn);
2497                 (close_chan_update_1, close_chan_update_2)
2498         };
2499         nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2500         nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2501         assert_eq!(nodes[3].node.list_channels().len(), 0);
2502         assert_eq!(nodes[4].node.list_channels().len(), 0);
2503 }
2504
2505 #[test]
2506 fn test_justice_tx() {
2507         // Test justice txn built on revoked HTLC-Success tx, against both sides
2508         let mut alice_config = UserConfig::default();
2509         alice_config.channel_options.announced_channel = true;
2510         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2511         alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2512         let mut bob_config = UserConfig::default();
2513         bob_config.channel_options.announced_channel = true;
2514         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2515         bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2516         let user_cfgs = [Some(alice_config), Some(bob_config)];
2517         let chanmon_cfgs = create_chanmon_cfgs(2);
2518         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2519         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2520         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2521         // Create some new channels:
2522         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2523
2524         // A pending HTLC which will be revoked:
2525         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2526         // Get the will-be-revoked local txn from nodes[0]
2527         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2528         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2529         assert_eq!(revoked_local_txn[0].input.len(), 1);
2530         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2531         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2532         assert_eq!(revoked_local_txn[1].input.len(), 1);
2533         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2534         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2535         // Revoke the old state
2536         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 3_000_000);
2537
2538         {
2539                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2540                 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2541                 {
2542                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2543                         assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2544                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2545
2546                         check_spends!(node_txn[0], revoked_local_txn[0]);
2547                         node_txn.swap_remove(0);
2548                         node_txn.truncate(1);
2549                 }
2550                 check_added_monitors!(nodes[1], 1);
2551                 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2552
2553                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2554                 // Verify broadcast of revoked HTLC-timeout
2555                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2556                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2557                 check_added_monitors!(nodes[0], 1);
2558                 // Broadcast revoked HTLC-timeout on node 1
2559                 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2560                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2561         }
2562         get_announce_close_broadcast_events(&nodes, 0, 1);
2563
2564         assert_eq!(nodes[0].node.list_channels().len(), 0);
2565         assert_eq!(nodes[1].node.list_channels().len(), 0);
2566
2567         // We test justice_tx build by A on B's revoked HTLC-Success tx
2568         // Create some new channels:
2569         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2570         {
2571                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2572                 node_txn.clear();
2573         }
2574
2575         // A pending HTLC which will be revoked:
2576         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2577         // Get the will-be-revoked local txn from B
2578         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2579         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2580         assert_eq!(revoked_local_txn[0].input.len(), 1);
2581         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2582         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2583         // Revoke the old state
2584         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4, 3_000_000);
2585         {
2586                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2587                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2588                 {
2589                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2590                         assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2591                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2592
2593                         check_spends!(node_txn[0], revoked_local_txn[0]);
2594                         node_txn.swap_remove(0);
2595                 }
2596                 check_added_monitors!(nodes[0], 1);
2597                 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2598
2599                 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2600                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2601                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2602                 check_added_monitors!(nodes[1], 1);
2603                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2604                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2605         }
2606         get_announce_close_broadcast_events(&nodes, 0, 1);
2607         assert_eq!(nodes[0].node.list_channels().len(), 0);
2608         assert_eq!(nodes[1].node.list_channels().len(), 0);
2609 }
2610
2611 #[test]
2612 fn revoked_output_claim() {
2613         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2614         // transaction is broadcast by its counterparty
2615         let chanmon_cfgs = create_chanmon_cfgs(2);
2616         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2617         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2618         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2619         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2620         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2621         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2622         assert_eq!(revoked_local_txn.len(), 1);
2623         // Only output is the full channel value back to nodes[0]:
2624         assert_eq!(revoked_local_txn[0].output.len(), 1);
2625         // Send a payment through, updating everyone's latest commitment txn
2626         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000, 5_000_000);
2627
2628         // Inform nodes[1] that nodes[0] broadcast a stale tx
2629         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2630         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2631         check_added_monitors!(nodes[1], 1);
2632         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2633         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2634
2635         check_spends!(node_txn[0], revoked_local_txn[0]);
2636         check_spends!(node_txn[1], chan_1.3);
2637
2638         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2639         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2640         get_announce_close_broadcast_events(&nodes, 0, 1);
2641         check_added_monitors!(nodes[0], 1)
2642 }
2643
2644 #[test]
2645 fn claim_htlc_outputs_shared_tx() {
2646         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2647         let chanmon_cfgs = create_chanmon_cfgs(2);
2648         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2649         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2650         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2651
2652         // Create some new channel:
2653         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2654
2655         // Rebalance the network to generate htlc in the two directions
2656         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2657         // 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
2658         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2659         let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2660
2661         // Get the will-be-revoked local txn from node[0]
2662         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2663         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2664         assert_eq!(revoked_local_txn[0].input.len(), 1);
2665         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2666         assert_eq!(revoked_local_txn[1].input.len(), 1);
2667         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2668         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2669         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2670
2671         //Revoke the old state
2672         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2673
2674         {
2675                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2676                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2677                 check_added_monitors!(nodes[0], 1);
2678                 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2679                 check_added_monitors!(nodes[1], 1);
2680                 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
2681                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2682
2683                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2684                 assert_eq!(node_txn.len(), 3); // ChannelMonitor: penalty tx, ChannelManager: local commitment + HTLC-timeout
2685
2686                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2687                 check_spends!(node_txn[0], revoked_local_txn[0]);
2688
2689                 let mut witness_lens = BTreeSet::new();
2690                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2691                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2692                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2693                 assert_eq!(witness_lens.len(), 3);
2694                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2695                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2696                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2697
2698                 // Next nodes[1] broadcasts its current local tx state:
2699                 assert_eq!(node_txn[1].input.len(), 1);
2700                 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2701
2702                 assert_eq!(node_txn[2].input.len(), 1);
2703                 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
2704                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2705                 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
2706                 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
2707                 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
2708         }
2709         get_announce_close_broadcast_events(&nodes, 0, 1);
2710         assert_eq!(nodes[0].node.list_channels().len(), 0);
2711         assert_eq!(nodes[1].node.list_channels().len(), 0);
2712 }
2713
2714 #[test]
2715 fn claim_htlc_outputs_single_tx() {
2716         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2717         let chanmon_cfgs = create_chanmon_cfgs(2);
2718         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2719         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2720         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2721
2722         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2723
2724         // Rebalance the network to generate htlc in the two directions
2725         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2726         // 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
2727         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2728         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2729         let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2730
2731         // Get the will-be-revoked local txn from node[0]
2732         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2733
2734         //Revoke the old state
2735         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2736
2737         {
2738                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2739                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2740                 check_added_monitors!(nodes[0], 1);
2741                 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2742                 check_added_monitors!(nodes[1], 1);
2743                 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
2744
2745                 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 200, true, header.block_hash());
2746                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2747
2748                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2749                 assert_eq!(node_txn.len(), 9);
2750                 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2751                 // ChannelManager: local commmitment + local HTLC-timeout (2)
2752                 // 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)
2753                 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2754
2755                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2756                 assert_eq!(node_txn[2].input.len(), 1);
2757                 check_spends!(node_txn[2], chan_1.3);
2758                 assert_eq!(node_txn[3].input.len(), 1);
2759                 let witness_script = node_txn[3].input[0].witness.last().unwrap();
2760                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2761                 check_spends!(node_txn[3], node_txn[2]);
2762
2763                 // Justice transactions are indices 1-2-4
2764                 assert_eq!(node_txn[0].input.len(), 1);
2765                 assert_eq!(node_txn[1].input.len(), 1);
2766                 assert_eq!(node_txn[4].input.len(), 1);
2767
2768                 check_spends!(node_txn[0], revoked_local_txn[0]);
2769                 check_spends!(node_txn[1], revoked_local_txn[0]);
2770                 check_spends!(node_txn[4], revoked_local_txn[0]);
2771
2772                 let mut witness_lens = BTreeSet::new();
2773                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2774                 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2775                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2776                 assert_eq!(witness_lens.len(), 3);
2777                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2778                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2779                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2780         }
2781         get_announce_close_broadcast_events(&nodes, 0, 1);
2782         assert_eq!(nodes[0].node.list_channels().len(), 0);
2783         assert_eq!(nodes[1].node.list_channels().len(), 0);
2784 }
2785
2786 #[test]
2787 fn test_htlc_on_chain_success() {
2788         // Test that in case of a unilateral close onchain, we detect the state of output thanks to
2789         // ChainWatchInterface and pass the preimage backward accordingly. So here we test that ChannelManager is
2790         // broadcasting the right event to other nodes in payment path.
2791         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2792         // A --------------------> B ----------------------> C (preimage)
2793         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2794         // commitment transaction was broadcast.
2795         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2796         // towards B.
2797         // B should be able to claim via preimage if A then broadcasts its local tx.
2798         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2799         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2800         // PaymentSent event).
2801
2802         let chanmon_cfgs = create_chanmon_cfgs(3);
2803         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2804         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2805         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2806
2807         // Create some initial channels
2808         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2809         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2810
2811         // Rebalance the network a bit by relaying one payment through all the channels...
2812         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2813         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2814
2815         let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2816         let (our_payment_preimage_2, _payment_hash_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2817         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2818
2819         // Broadcast legit commitment tx from C on B's chain
2820         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2821         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2822         assert_eq!(commitment_tx.len(), 1);
2823         check_spends!(commitment_tx[0], chan_2.3);
2824         nodes[2].node.claim_funds(our_payment_preimage, &None, 3_000_000);
2825         nodes[2].node.claim_funds(our_payment_preimage_2, &None, 3_000_000);
2826         check_added_monitors!(nodes[2], 2);
2827         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2828         assert!(updates.update_add_htlcs.is_empty());
2829         assert!(updates.update_fail_htlcs.is_empty());
2830         assert!(updates.update_fail_malformed_htlcs.is_empty());
2831         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2832
2833         nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2834         check_closed_broadcast!(nodes[2], false);
2835         check_added_monitors!(nodes[2], 1);
2836         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)
2837         assert_eq!(node_txn.len(), 5);
2838         assert_eq!(node_txn[0], node_txn[3]);
2839         assert_eq!(node_txn[1], node_txn[4]);
2840         assert_eq!(node_txn[2], commitment_tx[0]);
2841         check_spends!(node_txn[0], commitment_tx[0]);
2842         check_spends!(node_txn[1], commitment_tx[0]);
2843         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2844         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2845         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2846         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2847         assert_eq!(node_txn[0].lock_time, 0);
2848         assert_eq!(node_txn[1].lock_time, 0);
2849
2850         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2851         nodes[1].block_notifier.block_connected(&Block { header, txdata: node_txn}, 1);
2852         {
2853                 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
2854                 assert_eq!(added_monitors.len(), 1);
2855                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2856                 added_monitors.clear();
2857         }
2858         let events = nodes[1].node.get_and_clear_pending_msg_events();
2859         {
2860                 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
2861                 assert_eq!(added_monitors.len(), 2);
2862                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2863                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2864                 added_monitors.clear();
2865         }
2866         assert_eq!(events.len(), 2);
2867         match events[0] {
2868                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2869                 _ => panic!("Unexpected event"),
2870         }
2871         match events[1] {
2872                 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, .. } } => {
2873                         assert!(update_add_htlcs.is_empty());
2874                         assert!(update_fail_htlcs.is_empty());
2875                         assert_eq!(update_fulfill_htlcs.len(), 1);
2876                         assert!(update_fail_malformed_htlcs.is_empty());
2877                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2878                 },
2879                 _ => panic!("Unexpected event"),
2880         };
2881         macro_rules! check_tx_local_broadcast {
2882                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2883                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2884                         assert_eq!(node_txn.len(), 5);
2885                         // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2886                         // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2887                         check_spends!(node_txn[0], $commitment_tx);
2888                         check_spends!(node_txn[1], $commitment_tx);
2889                         assert_ne!(node_txn[0].lock_time, 0);
2890                         assert_ne!(node_txn[1].lock_time, 0);
2891                         if $htlc_offered {
2892                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2893                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2894                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2895                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2896                         } else {
2897                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2898                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2899                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2900                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2901                         }
2902                         check_spends!(node_txn[2], $chan_tx);
2903                         check_spends!(node_txn[3], node_txn[2]);
2904                         check_spends!(node_txn[4], node_txn[2]);
2905                         assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), 71);
2906                         assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2907                         assert_eq!(node_txn[4].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2908                         assert!(node_txn[3].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2909                         assert!(node_txn[4].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2910                         assert_ne!(node_txn[3].lock_time, 0);
2911                         assert_ne!(node_txn[4].lock_time, 0);
2912                         node_txn.clear();
2913                 } }
2914         }
2915         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2916         // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2917         // timeout-claim of the output that nodes[2] just claimed via success.
2918         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2919
2920         // Broadcast legit commitment tx from A on B's chain
2921         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2922         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2923         check_spends!(commitment_tx[0], chan_1.3);
2924         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2925         check_closed_broadcast!(nodes[1], false);
2926         check_added_monitors!(nodes[1], 1);
2927         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 1 (HTLC-Success)
2928         assert_eq!(node_txn.len(), 4);
2929         check_spends!(node_txn[0], commitment_tx[0]);
2930         assert_eq!(node_txn[0].input.len(), 2);
2931         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2932         assert_eq!(node_txn[0].input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2933         assert_eq!(node_txn[0].lock_time, 0);
2934         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2935         check_spends!(node_txn[1], chan_1.3);
2936         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
2937         check_spends!(node_txn[2], node_txn[1]);
2938         check_spends!(node_txn[3], node_txn[1]);
2939         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2940         // we already checked the same situation with A.
2941
2942         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2943         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
2944         check_closed_broadcast!(nodes[0], false);
2945         check_added_monitors!(nodes[0], 1);
2946         let events = nodes[0].node.get_and_clear_pending_events();
2947         assert_eq!(events.len(), 2);
2948         let mut first_claimed = false;
2949         for event in events {
2950                 match event {
2951                         Event::PaymentSent { payment_preimage } => {
2952                                 if payment_preimage == our_payment_preimage {
2953                                         assert!(!first_claimed);
2954                                         first_claimed = true;
2955                                 } else {
2956                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2957                                 }
2958                         },
2959                         _ => panic!("Unexpected event"),
2960                 }
2961         }
2962         check_tx_local_broadcast!(nodes[0], true, commitment_tx[0], chan_1.3);
2963 }
2964
2965 #[test]
2966 fn test_htlc_on_chain_timeout() {
2967         // Test that in case of a unilateral close onchain, we detect the state of output thanks to
2968         // ChainWatchInterface and timeout the HTLC backward accordingly. So here we test that ChannelManager is
2969         // broadcasting the right event to other nodes in payment path.
2970         // A ------------------> B ----------------------> C (timeout)
2971         //    B's commitment tx                 C's commitment tx
2972         //            \                                  \
2973         //         B's HTLC timeout tx               B's timeout tx
2974
2975         let chanmon_cfgs = create_chanmon_cfgs(3);
2976         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2977         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2978         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2979
2980         // Create some intial channels
2981         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2982         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2983
2984         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2985         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2986         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2987
2988         let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2989         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2990
2991         // Broadcast legit commitment tx from C on B's chain
2992         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2993         check_spends!(commitment_tx[0], chan_2.3);
2994         nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
2995         check_added_monitors!(nodes[2], 0);
2996         expect_pending_htlcs_forwardable!(nodes[2]);
2997         check_added_monitors!(nodes[2], 1);
2998
2999         let events = nodes[2].node.get_and_clear_pending_msg_events();
3000         assert_eq!(events.len(), 1);
3001         match events[0] {
3002                 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, .. } } => {
3003                         assert!(update_add_htlcs.is_empty());
3004                         assert!(!update_fail_htlcs.is_empty());
3005                         assert!(update_fulfill_htlcs.is_empty());
3006                         assert!(update_fail_malformed_htlcs.is_empty());
3007                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
3008                 },
3009                 _ => panic!("Unexpected event"),
3010         };
3011         nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
3012         check_closed_broadcast!(nodes[2], false);
3013         check_added_monitors!(nodes[2], 1);
3014         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
3015         assert_eq!(node_txn.len(), 1);
3016         check_spends!(node_txn[0], chan_2.3);
3017         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
3018
3019         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
3020         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
3021         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
3022         let timeout_tx;
3023         {
3024                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3025                 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
3026                 assert_eq!(node_txn[1], node_txn[3]);
3027                 assert_eq!(node_txn[2], node_txn[4]);
3028
3029                 check_spends!(node_txn[0], commitment_tx[0]);
3030                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3031
3032                 check_spends!(node_txn[1], chan_2.3);
3033                 check_spends!(node_txn[2], node_txn[1]);
3034                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
3035                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3036
3037                 timeout_tx = node_txn[0].clone();
3038                 node_txn.clear();
3039         }
3040
3041         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![timeout_tx]}, 1);
3042         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
3043         check_added_monitors!(nodes[1], 1);
3044         check_closed_broadcast!(nodes[1], false);
3045
3046         expect_pending_htlcs_forwardable!(nodes[1]);
3047         check_added_monitors!(nodes[1], 1);
3048         let events = nodes[1].node.get_and_clear_pending_msg_events();
3049         assert_eq!(events.len(), 1);
3050         match events[0] {
3051                 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, .. } } => {
3052                         assert!(update_add_htlcs.is_empty());
3053                         assert!(!update_fail_htlcs.is_empty());
3054                         assert!(update_fulfill_htlcs.is_empty());
3055                         assert!(update_fail_malformed_htlcs.is_empty());
3056                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3057                 },
3058                 _ => panic!("Unexpected event"),
3059         };
3060         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
3061         assert_eq!(node_txn.len(), 0);
3062
3063         // Broadcast legit commitment tx from B on A's chain
3064         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3065         check_spends!(commitment_tx[0], chan_1.3);
3066
3067         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
3068         check_closed_broadcast!(nodes[0], false);
3069         check_added_monitors!(nodes[0], 1);
3070         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 1 timeout tx
3071         assert_eq!(node_txn.len(), 3);
3072         check_spends!(node_txn[0], commitment_tx[0]);
3073         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3074         check_spends!(node_txn[1], chan_1.3);
3075         check_spends!(node_txn[2], node_txn[1]);
3076         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
3077         assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3078 }
3079
3080 #[test]
3081 fn test_simple_commitment_revoked_fail_backward() {
3082         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3083         // and fail backward accordingly.
3084
3085         let chanmon_cfgs = create_chanmon_cfgs(3);
3086         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3087         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3088         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3089
3090         // Create some initial channels
3091         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3092         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3093
3094         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3095         // Get the will-be-revoked local txn from nodes[2]
3096         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3097         // Revoke the old state
3098         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, 3_000_000);
3099
3100         let (_, payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3101
3102         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
3103         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3104         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
3105         check_added_monitors!(nodes[1], 1);
3106         check_closed_broadcast!(nodes[1], false);
3107
3108         expect_pending_htlcs_forwardable!(nodes[1]);
3109         check_added_monitors!(nodes[1], 1);
3110         let events = nodes[1].node.get_and_clear_pending_msg_events();
3111         assert_eq!(events.len(), 1);
3112         match events[0] {
3113                 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, .. } } => {
3114                         assert!(update_add_htlcs.is_empty());
3115                         assert_eq!(update_fail_htlcs.len(), 1);
3116                         assert!(update_fulfill_htlcs.is_empty());
3117                         assert!(update_fail_malformed_htlcs.is_empty());
3118                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3119
3120                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3121                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3122
3123                         let events = nodes[0].node.get_and_clear_pending_msg_events();
3124                         assert_eq!(events.len(), 1);
3125                         match events[0] {
3126                                 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3127                                 _ => panic!("Unexpected event"),
3128                         }
3129                         expect_payment_failed!(nodes[0], payment_hash, false);
3130                 },
3131                 _ => panic!("Unexpected event"),
3132         }
3133 }
3134
3135 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3136         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3137         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3138         // commitment transaction anymore.
3139         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3140         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3141         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3142         // technically disallowed and we should probably handle it reasonably.
3143         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3144         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3145         // transactions:
3146         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3147         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3148         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3149         //   and once they revoke the previous commitment transaction (allowing us to send a new
3150         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3151         let chanmon_cfgs = create_chanmon_cfgs(3);
3152         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3153         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3154         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3155
3156         // Create some initial channels
3157         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3158         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3159
3160         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3161         // Get the will-be-revoked local txn from nodes[2]
3162         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3163         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3164         // Revoke the old state
3165         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, if no_to_remote { 10_000 } else { 3_000_000});
3166
3167         let value = if use_dust {
3168                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3169                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3170                 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3171         } else { 3000000 };
3172
3173         let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3174         let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3175         let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3176
3177         assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, &None));
3178         expect_pending_htlcs_forwardable!(nodes[2]);
3179         check_added_monitors!(nodes[2], 1);
3180         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3181         assert!(updates.update_add_htlcs.is_empty());
3182         assert!(updates.update_fulfill_htlcs.is_empty());
3183         assert!(updates.update_fail_malformed_htlcs.is_empty());
3184         assert_eq!(updates.update_fail_htlcs.len(), 1);
3185         assert!(updates.update_fee.is_none());
3186         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3187         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3188         // Drop the last RAA from 3 -> 2
3189
3190         assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, &None));
3191         expect_pending_htlcs_forwardable!(nodes[2]);
3192         check_added_monitors!(nodes[2], 1);
3193         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3194         assert!(updates.update_add_htlcs.is_empty());
3195         assert!(updates.update_fulfill_htlcs.is_empty());
3196         assert!(updates.update_fail_malformed_htlcs.is_empty());
3197         assert_eq!(updates.update_fail_htlcs.len(), 1);
3198         assert!(updates.update_fee.is_none());
3199         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3200         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3201         check_added_monitors!(nodes[1], 1);
3202         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3203         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3204         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3205         check_added_monitors!(nodes[2], 1);
3206
3207         assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, &None));
3208         expect_pending_htlcs_forwardable!(nodes[2]);
3209         check_added_monitors!(nodes[2], 1);
3210         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3211         assert!(updates.update_add_htlcs.is_empty());
3212         assert!(updates.update_fulfill_htlcs.is_empty());
3213         assert!(updates.update_fail_malformed_htlcs.is_empty());
3214         assert_eq!(updates.update_fail_htlcs.len(), 1);
3215         assert!(updates.update_fee.is_none());
3216         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3217         // At this point first_payment_hash has dropped out of the latest two commitment
3218         // transactions that nodes[1] is tracking...
3219         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3220         check_added_monitors!(nodes[1], 1);
3221         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3222         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3223         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3224         check_added_monitors!(nodes[2], 1);
3225
3226         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3227         // on nodes[2]'s RAA.
3228         let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3229         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3230         let logger = test_utils::TestLogger::new();
3231         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();
3232         nodes[1].node.send_payment(&route, fourth_payment_hash, &None).unwrap();
3233         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3234         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3235         check_added_monitors!(nodes[1], 0);
3236
3237         if deliver_bs_raa {
3238                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3239                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3240                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3241                 check_added_monitors!(nodes[1], 1);
3242                 let events = nodes[1].node.get_and_clear_pending_events();
3243                 assert_eq!(events.len(), 1);
3244                 match events[0] {
3245                         Event::PendingHTLCsForwardable { .. } => { },
3246                         _ => panic!("Unexpected event"),
3247                 };
3248                 // Deliberately don't process the pending fail-back so they all fail back at once after
3249                 // block connection just like the !deliver_bs_raa case
3250         }
3251
3252         let mut failed_htlcs = HashSet::new();
3253         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3254
3255         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
3256         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3257         check_added_monitors!(nodes[1], 1);
3258         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
3259
3260         let events = nodes[1].node.get_and_clear_pending_events();
3261         assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
3262         match events[0] {
3263                 Event::PaymentFailed { ref payment_hash, .. } => {
3264                         assert_eq!(*payment_hash, fourth_payment_hash);
3265                 },
3266                 _ => panic!("Unexpected event"),
3267         }
3268         if !deliver_bs_raa {
3269                 match events[1] {
3270                         Event::PendingHTLCsForwardable { .. } => { },
3271                         _ => panic!("Unexpected event"),
3272                 };
3273         }
3274         nodes[1].node.process_pending_htlc_forwards();
3275         check_added_monitors!(nodes[1], 1);
3276
3277         let events = nodes[1].node.get_and_clear_pending_msg_events();
3278         assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
3279         match events[if deliver_bs_raa { 1 } else { 0 }] {
3280                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3281                 _ => panic!("Unexpected event"),
3282         }
3283         if deliver_bs_raa {
3284                 match events[0] {
3285                         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, .. } } => {
3286                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3287                                 assert_eq!(update_add_htlcs.len(), 1);
3288                                 assert!(update_fulfill_htlcs.is_empty());
3289                                 assert!(update_fail_htlcs.is_empty());
3290                                 assert!(update_fail_malformed_htlcs.is_empty());
3291                         },
3292                         _ => panic!("Unexpected event"),
3293                 }
3294         }
3295         match events[if deliver_bs_raa { 2 } else { 1 }] {
3296                 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, .. } } => {
3297                         assert!(update_add_htlcs.is_empty());
3298                         assert_eq!(update_fail_htlcs.len(), 3);
3299                         assert!(update_fulfill_htlcs.is_empty());
3300                         assert!(update_fail_malformed_htlcs.is_empty());
3301                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3302
3303                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3304                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3305                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3306
3307                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3308
3309                         let events = nodes[0].node.get_and_clear_pending_msg_events();
3310                         // If we delivered B's RAA we got an unknown preimage error, not something
3311                         // that we should update our routing table for.
3312                         assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
3313                         for event in events {
3314                                 match event {
3315                                         MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3316                                         _ => panic!("Unexpected event"),
3317                                 }
3318                         }
3319                         let events = nodes[0].node.get_and_clear_pending_events();
3320                         assert_eq!(events.len(), 3);
3321                         match events[0] {
3322                                 Event::PaymentFailed { ref payment_hash, .. } => {
3323                                         assert!(failed_htlcs.insert(payment_hash.0));
3324                                 },
3325                                 _ => panic!("Unexpected event"),
3326                         }
3327                         match events[1] {
3328                                 Event::PaymentFailed { ref payment_hash, .. } => {
3329                                         assert!(failed_htlcs.insert(payment_hash.0));
3330                                 },
3331                                 _ => panic!("Unexpected event"),
3332                         }
3333                         match events[2] {
3334                                 Event::PaymentFailed { ref payment_hash, .. } => {
3335                                         assert!(failed_htlcs.insert(payment_hash.0));
3336                                 },
3337                                 _ => panic!("Unexpected event"),
3338                         }
3339                 },
3340                 _ => panic!("Unexpected event"),
3341         }
3342
3343         assert!(failed_htlcs.contains(&first_payment_hash.0));
3344         assert!(failed_htlcs.contains(&second_payment_hash.0));
3345         assert!(failed_htlcs.contains(&third_payment_hash.0));
3346 }
3347
3348 #[test]
3349 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3350         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3351         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3352         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3353         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3354 }
3355
3356 #[test]
3357 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3358         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3359         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3360         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3361         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3362 }
3363
3364 #[test]
3365 fn fail_backward_pending_htlc_upon_channel_failure() {
3366         let chanmon_cfgs = create_chanmon_cfgs(2);
3367         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3368         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3369         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3370         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3371         let logger = test_utils::TestLogger::new();
3372
3373         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3374         {
3375                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
3376                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3377                 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();
3378                 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
3379                 check_added_monitors!(nodes[0], 1);
3380
3381                 let payment_event = {
3382                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3383                         assert_eq!(events.len(), 1);
3384                         SendEvent::from_event(events.remove(0))
3385                 };
3386                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3387                 assert_eq!(payment_event.msgs.len(), 1);
3388         }
3389
3390         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3391         let (_, failed_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3392         {
3393                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3394                 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();
3395                 nodes[0].node.send_payment(&route, failed_payment_hash, &None).unwrap();
3396                 check_added_monitors!(nodes[0], 0);
3397
3398                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3399         }
3400
3401         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3402         {
3403                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[1]);
3404
3405                 let secp_ctx = Secp256k1::new();
3406                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3407                 let current_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
3408                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3409                 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();
3410                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &None, current_height).unwrap();
3411                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3412                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3413
3414                 // Send a 0-msat update_add_htlc to fail the channel.
3415                 let update_add_htlc = msgs::UpdateAddHTLC {
3416                         channel_id: chan.2,
3417                         htlc_id: 0,
3418                         amount_msat: 0,
3419                         payment_hash,
3420                         cltv_expiry,
3421                         onion_routing_packet,
3422                 };
3423                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3424         }
3425
3426         // Check that Alice fails backward the pending HTLC from the second payment.
3427         expect_payment_failed!(nodes[0], failed_payment_hash, true);
3428         check_closed_broadcast!(nodes[0], true);
3429         check_added_monitors!(nodes[0], 1);
3430 }
3431
3432 #[test]
3433 fn test_htlc_ignore_latest_remote_commitment() {
3434         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3435         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3436         let chanmon_cfgs = create_chanmon_cfgs(2);
3437         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3438         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3439         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3440         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3441
3442         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3443         nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
3444         check_closed_broadcast!(nodes[0], false);
3445         check_added_monitors!(nodes[0], 1);
3446
3447         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3448         assert_eq!(node_txn.len(), 2);
3449
3450         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3451         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3452         check_closed_broadcast!(nodes[1], false);
3453         check_added_monitors!(nodes[1], 1);
3454
3455         // Duplicate the block_connected call since this may happen due to other listeners
3456         // registering new transactions
3457         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3458 }
3459
3460 #[test]
3461 fn test_force_close_fail_back() {
3462         // Check which HTLCs are failed-backwards on channel force-closure
3463         let chanmon_cfgs = create_chanmon_cfgs(3);
3464         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3465         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3466         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3467         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3468         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3469         let logger = test_utils::TestLogger::new();
3470
3471         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3472
3473         let mut payment_event = {
3474                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3475                 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();
3476                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
3477                 check_added_monitors!(nodes[0], 1);
3478
3479                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3480                 assert_eq!(events.len(), 1);
3481                 SendEvent::from_event(events.remove(0))
3482         };
3483
3484         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3485         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3486
3487         expect_pending_htlcs_forwardable!(nodes[1]);
3488
3489         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3490         assert_eq!(events_2.len(), 1);
3491         payment_event = SendEvent::from_event(events_2.remove(0));
3492         assert_eq!(payment_event.msgs.len(), 1);
3493
3494         check_added_monitors!(nodes[1], 1);
3495         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3496         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3497         check_added_monitors!(nodes[2], 1);
3498         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3499
3500         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3501         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3502         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3503
3504         nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
3505         check_closed_broadcast!(nodes[2], false);
3506         check_added_monitors!(nodes[2], 1);
3507         let tx = {
3508                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3509                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3510                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3511                 // back to nodes[1] upon timeout otherwise.
3512                 assert_eq!(node_txn.len(), 1);
3513                 node_txn.remove(0)
3514         };
3515
3516         let block = Block {
3517                 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
3518                 txdata: vec![tx.clone()],
3519         };
3520         nodes[1].block_notifier.block_connected(&block, 1);
3521
3522         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3523         check_closed_broadcast!(nodes[1], false);
3524         check_added_monitors!(nodes[1], 1);
3525
3526         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3527         {
3528                 let mut monitors = nodes[2].chan_monitor.simple_monitor.monitors.lock().unwrap();
3529                 monitors.get_mut(&OutPoint{ txid: Txid::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), index: 0 }).unwrap()
3530                         .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
3531         }
3532         nodes[2].block_notifier.block_connected(&block, 1);
3533         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3534         assert_eq!(node_txn.len(), 1);
3535         assert_eq!(node_txn[0].input.len(), 1);
3536         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3537         assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3538         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3539
3540         check_spends!(node_txn[0], tx);
3541 }
3542
3543 #[test]
3544 fn test_unconf_chan() {
3545         // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
3546         let chanmon_cfgs = create_chanmon_cfgs(2);
3547         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3548         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3549         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3550         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3551
3552         let channel_state = nodes[0].node.channel_state.lock().unwrap();
3553         assert_eq!(channel_state.by_id.len(), 1);
3554         assert_eq!(channel_state.short_to_id.len(), 1);
3555         mem::drop(channel_state);
3556
3557         let mut headers = Vec::new();
3558         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3559         headers.push(header.clone());
3560         for _i in 2..100 {
3561                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3562                 headers.push(header.clone());
3563         }
3564         let mut height = 99;
3565         while !headers.is_empty() {
3566                 nodes[0].node.block_disconnected(&headers.pop().unwrap(), height);
3567                 height -= 1;
3568         }
3569         check_closed_broadcast!(nodes[0], false);
3570         check_added_monitors!(nodes[0], 1);
3571         let channel_state = nodes[0].node.channel_state.lock().unwrap();
3572         assert_eq!(channel_state.by_id.len(), 0);
3573         assert_eq!(channel_state.short_to_id.len(), 0);
3574 }
3575
3576 #[test]
3577 fn test_simple_peer_disconnect() {
3578         // Test that we can reconnect when there are no lost messages
3579         let chanmon_cfgs = create_chanmon_cfgs(3);
3580         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3581         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3582         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3583         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3584         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3585
3586         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3587         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3588         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3589
3590         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3591         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3592         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3593         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1, 1_000_000);
3594
3595         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3596         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3597         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3598
3599         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3600         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3601         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3602         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3603
3604         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3605         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3606
3607         claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3, 1_000_000);
3608         fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
3609
3610         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3611         {
3612                 let events = nodes[0].node.get_and_clear_pending_events();
3613                 assert_eq!(events.len(), 2);
3614                 match events[0] {
3615                         Event::PaymentSent { payment_preimage } => {
3616                                 assert_eq!(payment_preimage, payment_preimage_3);
3617                         },
3618                         _ => panic!("Unexpected event"),
3619                 }
3620                 match events[1] {
3621                         Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
3622                                 assert_eq!(payment_hash, payment_hash_5);
3623                                 assert!(rejected_by_dest);
3624                         },
3625                         _ => panic!("Unexpected event"),
3626                 }
3627         }
3628
3629         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4, 1_000_000);
3630         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3631 }
3632
3633 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
3634         // Test that we can reconnect when in-flight HTLC updates get dropped
3635         let chanmon_cfgs = create_chanmon_cfgs(2);
3636         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3637         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3638         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3639         if messages_delivered == 0 {
3640                 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3641                 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3642         } else {
3643                 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3644         }
3645
3646         let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
3647
3648         let logger = test_utils::TestLogger::new();
3649         let payment_event = {
3650                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3651                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3652                         &nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3653                         &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3654                 nodes[0].node.send_payment(&route, payment_hash_1, &None).unwrap();
3655                 check_added_monitors!(nodes[0], 1);
3656
3657                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3658                 assert_eq!(events.len(), 1);
3659                 SendEvent::from_event(events.remove(0))
3660         };
3661         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3662
3663         if messages_delivered < 2 {
3664                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3665         } else {
3666                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3667                 if messages_delivered >= 3 {
3668                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3669                         check_added_monitors!(nodes[1], 1);
3670                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3671
3672                         if messages_delivered >= 4 {
3673                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3674                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3675                                 check_added_monitors!(nodes[0], 1);
3676
3677                                 if messages_delivered >= 5 {
3678                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3679                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3680                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3681                                         check_added_monitors!(nodes[0], 1);
3682
3683                                         if messages_delivered >= 6 {
3684                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3685                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3686                                                 check_added_monitors!(nodes[1], 1);
3687                                         }
3688                                 }
3689                         }
3690                 }
3691         }
3692
3693         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3694         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3695         if messages_delivered < 3 {
3696                 // Even if the funding_locked messages get exchanged, as long as nothing further was
3697                 // received on either side, both sides will need to resend them.
3698                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
3699         } else if messages_delivered == 3 {
3700                 // nodes[0] still wants its RAA + commitment_signed
3701                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
3702         } else if messages_delivered == 4 {
3703                 // nodes[0] still wants its commitment_signed
3704                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3705         } else if messages_delivered == 5 {
3706                 // nodes[1] still wants its final RAA
3707                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3708         } else if messages_delivered == 6 {
3709                 // Everything was delivered...
3710                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3711         }
3712
3713         let events_1 = nodes[1].node.get_and_clear_pending_events();
3714         assert_eq!(events_1.len(), 1);
3715         match events_1[0] {
3716                 Event::PendingHTLCsForwardable { .. } => { },
3717                 _ => panic!("Unexpected event"),
3718         };
3719
3720         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3721         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3722         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3723
3724         nodes[1].node.process_pending_htlc_forwards();
3725
3726         let events_2 = nodes[1].node.get_and_clear_pending_events();
3727         assert_eq!(events_2.len(), 1);
3728         match events_2[0] {
3729                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
3730                         assert_eq!(payment_hash_1, *payment_hash);
3731                         assert_eq!(*payment_secret, None);
3732                         assert_eq!(amt, 1000000);
3733                 },
3734                 _ => panic!("Unexpected event"),
3735         }
3736
3737         nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000);
3738         check_added_monitors!(nodes[1], 1);
3739
3740         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3741         assert_eq!(events_3.len(), 1);
3742         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3743                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3744                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3745                         assert!(updates.update_add_htlcs.is_empty());
3746                         assert!(updates.update_fail_htlcs.is_empty());
3747                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3748                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3749                         assert!(updates.update_fee.is_none());
3750                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3751                 },
3752                 _ => panic!("Unexpected event"),
3753         };
3754
3755         if messages_delivered >= 1 {
3756                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3757
3758                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3759                 assert_eq!(events_4.len(), 1);
3760                 match events_4[0] {
3761                         Event::PaymentSent { ref payment_preimage } => {
3762                                 assert_eq!(payment_preimage_1, *payment_preimage);
3763                         },
3764                         _ => panic!("Unexpected event"),
3765                 }
3766
3767                 if messages_delivered >= 2 {
3768                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3769                         check_added_monitors!(nodes[0], 1);
3770                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3771
3772                         if messages_delivered >= 3 {
3773                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3774                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3775                                 check_added_monitors!(nodes[1], 1);
3776
3777                                 if messages_delivered >= 4 {
3778                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3779                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3780                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3781                                         check_added_monitors!(nodes[1], 1);
3782
3783                                         if messages_delivered >= 5 {
3784                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3785                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3786                                                 check_added_monitors!(nodes[0], 1);
3787                                         }
3788                                 }
3789                         }
3790                 }
3791         }
3792
3793         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3794         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3795         if messages_delivered < 2 {
3796                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
3797                 //TODO: Deduplicate PaymentSent events, then enable this if:
3798                 //if messages_delivered < 1 {
3799                         let events_4 = nodes[0].node.get_and_clear_pending_events();
3800                         assert_eq!(events_4.len(), 1);
3801                         match events_4[0] {
3802                                 Event::PaymentSent { ref payment_preimage } => {
3803                                         assert_eq!(payment_preimage_1, *payment_preimage);
3804                                 },
3805                                 _ => panic!("Unexpected event"),
3806                         }
3807                 //}
3808         } else if messages_delivered == 2 {
3809                 // nodes[0] still wants its RAA + commitment_signed
3810                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
3811         } else if messages_delivered == 3 {
3812                 // nodes[0] still wants its commitment_signed
3813                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
3814         } else if messages_delivered == 4 {
3815                 // nodes[1] still wants its final RAA
3816                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3817         } else if messages_delivered == 5 {
3818                 // Everything was delivered...
3819                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3820         }
3821
3822         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3823         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3824         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3825
3826         // Channel should still work fine...
3827         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3828         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3829                 &nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3830                 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3831         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3832         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3833 }
3834
3835 #[test]
3836 fn test_drop_messages_peer_disconnect_a() {
3837         do_test_drop_messages_peer_disconnect(0);
3838         do_test_drop_messages_peer_disconnect(1);
3839         do_test_drop_messages_peer_disconnect(2);
3840         do_test_drop_messages_peer_disconnect(3);
3841 }
3842
3843 #[test]
3844 fn test_drop_messages_peer_disconnect_b() {
3845         do_test_drop_messages_peer_disconnect(4);
3846         do_test_drop_messages_peer_disconnect(5);
3847         do_test_drop_messages_peer_disconnect(6);
3848 }
3849
3850 #[test]
3851 fn test_funding_peer_disconnect() {
3852         // Test that we can lock in our funding tx while disconnected
3853         let chanmon_cfgs = create_chanmon_cfgs(2);
3854         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3855         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3856         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3857         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3858
3859         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3860         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3861
3862         confirm_transaction(&nodes[0].block_notifier, &tx);
3863         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3864         assert_eq!(events_1.len(), 1);
3865         match events_1[0] {
3866                 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3867                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3868                 },
3869                 _ => panic!("Unexpected event"),
3870         }
3871
3872         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3873
3874         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3875         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3876
3877         confirm_transaction(&nodes[1].block_notifier, &tx);
3878         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3879         assert_eq!(events_2.len(), 2);
3880         let funding_locked = match events_2[0] {
3881                 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3882                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3883                         msg.clone()
3884                 },
3885                 _ => panic!("Unexpected event"),
3886         };
3887         let bs_announcement_sigs = match events_2[1] {
3888                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3889                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3890                         msg.clone()
3891                 },
3892                 _ => panic!("Unexpected event"),
3893         };
3894
3895         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3896
3897         nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3898         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3899         let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3900         assert_eq!(events_3.len(), 2);
3901         let as_announcement_sigs = match events_3[0] {
3902                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3903                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3904                         msg.clone()
3905                 },
3906                 _ => panic!("Unexpected event"),
3907         };
3908         let (as_announcement, as_update) = match events_3[1] {
3909                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3910                         (msg.clone(), update_msg.clone())
3911                 },
3912                 _ => panic!("Unexpected event"),
3913         };
3914
3915         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3916         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3917         assert_eq!(events_4.len(), 1);
3918         let (_, bs_update) = match events_4[0] {
3919                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3920                         (msg.clone(), update_msg.clone())
3921                 },
3922                 _ => panic!("Unexpected event"),
3923         };
3924
3925         nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3926         nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3927         nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3928
3929         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3930         let logger = test_utils::TestLogger::new();
3931         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();
3932         let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3933         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage, 1_000_000);
3934 }
3935
3936 #[test]
3937 fn test_drop_messages_peer_disconnect_dual_htlc() {
3938         // Test that we can handle reconnecting when both sides of a channel have pending
3939         // commitment_updates when we disconnect.
3940         let chanmon_cfgs = create_chanmon_cfgs(2);
3941         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3942         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3943         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3944         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3945         let logger = test_utils::TestLogger::new();
3946
3947         let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3948
3949         // Now try to send a second payment which will fail to send
3950         let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
3951         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3952         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();
3953         nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
3954         check_added_monitors!(nodes[0], 1);
3955
3956         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3957         assert_eq!(events_1.len(), 1);
3958         match events_1[0] {
3959                 MessageSendEvent::UpdateHTLCs { .. } => {},
3960                 _ => panic!("Unexpected event"),
3961         }
3962
3963         assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000));
3964         check_added_monitors!(nodes[1], 1);
3965
3966         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3967         assert_eq!(events_2.len(), 1);
3968         match events_2[0] {
3969                 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 } } => {
3970                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3971                         assert!(update_add_htlcs.is_empty());
3972                         assert_eq!(update_fulfill_htlcs.len(), 1);
3973                         assert!(update_fail_htlcs.is_empty());
3974                         assert!(update_fail_malformed_htlcs.is_empty());
3975                         assert!(update_fee.is_none());
3976
3977                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3978                         let events_3 = nodes[0].node.get_and_clear_pending_events();
3979                         assert_eq!(events_3.len(), 1);
3980                         match events_3[0] {
3981                                 Event::PaymentSent { ref payment_preimage } => {
3982                                         assert_eq!(*payment_preimage, payment_preimage_1);
3983                                 },
3984                                 _ => panic!("Unexpected event"),
3985                         }
3986
3987                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3988                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3989                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3990                         check_added_monitors!(nodes[0], 1);
3991                 },
3992                 _ => panic!("Unexpected event"),
3993         }
3994
3995         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3996         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3997
3998         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3999         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4000         assert_eq!(reestablish_1.len(), 1);
4001         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4002         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4003         assert_eq!(reestablish_2.len(), 1);
4004
4005         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4006         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4007         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4008         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4009
4010         assert!(as_resp.0.is_none());
4011         assert!(bs_resp.0.is_none());
4012
4013         assert!(bs_resp.1.is_none());
4014         assert!(bs_resp.2.is_none());
4015
4016         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4017
4018         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4019         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4020         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4021         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4022         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4023         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4024         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4025         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4026         // No commitment_signed so get_event_msg's assert(len == 1) passes
4027         check_added_monitors!(nodes[1], 1);
4028
4029         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4030         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4031         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4032         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4033         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4034         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4035         assert!(bs_second_commitment_signed.update_fee.is_none());
4036         check_added_monitors!(nodes[1], 1);
4037
4038         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4039         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4040         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4041         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4042         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4043         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4044         assert!(as_commitment_signed.update_fee.is_none());
4045         check_added_monitors!(nodes[0], 1);
4046
4047         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4048         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4049         // No commitment_signed so get_event_msg's assert(len == 1) passes
4050         check_added_monitors!(nodes[0], 1);
4051
4052         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4053         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4054         // No commitment_signed so get_event_msg's assert(len == 1) passes
4055         check_added_monitors!(nodes[1], 1);
4056
4057         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4058         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4059         check_added_monitors!(nodes[1], 1);
4060
4061         expect_pending_htlcs_forwardable!(nodes[1]);
4062
4063         let events_5 = nodes[1].node.get_and_clear_pending_events();
4064         assert_eq!(events_5.len(), 1);
4065         match events_5[0] {
4066                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt: _ } => {
4067                         assert_eq!(payment_hash_2, *payment_hash);
4068                         assert_eq!(*payment_secret, None);
4069                 },
4070                 _ => panic!("Unexpected event"),
4071         }
4072
4073         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4074         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4075         check_added_monitors!(nodes[0], 1);
4076
4077         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
4078 }
4079
4080 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4081         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4082         // to avoid our counterparty failing the channel.
4083         let chanmon_cfgs = create_chanmon_cfgs(2);
4084         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4085         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4086         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4087
4088         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4089         let logger = test_utils::TestLogger::new();
4090
4091         let our_payment_hash = if send_partial_mpp {
4092                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4093                 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();
4094                 let (_, our_payment_hash) = get_payment_preimage_hash!(&nodes[0]);
4095                 let payment_secret = PaymentSecret([0xdb; 32]);
4096                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4097                 // indicates there are more HTLCs coming.
4098                 nodes[0].node.send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200000, CHAN_CONFIRM_DEPTH).unwrap();
4099                 check_added_monitors!(nodes[0], 1);
4100                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4101                 assert_eq!(events.len(), 1);
4102                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4103                 // hop should *not* yet generate any PaymentReceived event(s).
4104                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false);
4105                 our_payment_hash
4106         } else {
4107                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4108         };
4109
4110         let mut block = Block {
4111                 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4112                 txdata: vec![],
4113         };
4114         nodes[0].block_notifier.block_connected(&block, 101);
4115         nodes[1].block_notifier.block_connected(&block, 101);
4116         for i in 102..TEST_FINAL_CLTV + 100 + 1 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
4117                 block.header.prev_blockhash = block.block_hash();
4118                 nodes[0].block_notifier.block_connected(&block, i);
4119                 nodes[1].block_notifier.block_connected(&block, i);
4120         }
4121
4122         expect_pending_htlcs_forwardable!(nodes[1]);
4123
4124         check_added_monitors!(nodes[1], 1);
4125         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4126         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4127         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4128         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4129         assert!(htlc_timeout_updates.update_fee.is_none());
4130
4131         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4132         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4133         // 100_000 msat as u64, followed by a height of 123 as u32
4134         let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4135         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(123));
4136         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4137 }
4138
4139 #[test]
4140 fn test_htlc_timeout() {
4141         do_test_htlc_timeout(true);
4142         do_test_htlc_timeout(false);
4143 }
4144
4145 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4146         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4147         let chanmon_cfgs = create_chanmon_cfgs(3);
4148         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4149         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4150         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4151         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4152         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4153         let logger = test_utils::TestLogger::new();
4154
4155         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4156         let (_, first_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4157         {
4158                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4159                 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();
4160                 nodes[1].node.send_payment(&route, first_payment_hash, &None).unwrap();
4161         }
4162         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4163         check_added_monitors!(nodes[1], 1);
4164
4165         // Now attempt to route a second payment, which should be placed in the holding cell
4166         let (_, second_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4167         if forwarded_htlc {
4168                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4169                 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();
4170                 nodes[0].node.send_payment(&route, second_payment_hash, &None).unwrap();
4171                 check_added_monitors!(nodes[0], 1);
4172                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4173                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4174                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4175                 expect_pending_htlcs_forwardable!(nodes[1]);
4176                 check_added_monitors!(nodes[1], 0);
4177         } else {
4178                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4179                 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();
4180                 nodes[1].node.send_payment(&route, second_payment_hash, &None).unwrap();
4181                 check_added_monitors!(nodes[1], 0);
4182         }
4183
4184         let mut block = Block {
4185                 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4186                 txdata: vec![],
4187         };
4188         nodes[1].block_notifier.block_connected(&block, 101);
4189         for i in 102..TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
4190                 block.header.prev_blockhash = block.block_hash();
4191                 nodes[1].block_notifier.block_connected(&block, i);
4192         }
4193
4194         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4195         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4196
4197         block.header.prev_blockhash = block.block_hash();
4198         nodes[1].block_notifier.block_connected(&block, TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS);
4199
4200         if forwarded_htlc {
4201                 expect_pending_htlcs_forwardable!(nodes[1]);
4202                 check_added_monitors!(nodes[1], 1);
4203                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4204                 assert_eq!(fail_commit.len(), 1);
4205                 match fail_commit[0] {
4206                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4207                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4208                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4209                         },
4210                         _ => unreachable!(),
4211                 }
4212                 expect_payment_failed!(nodes[0], second_payment_hash, false);
4213                 if let &MessageSendEvent::PaymentFailureNetworkUpdate { ref update } = &nodes[0].node.get_and_clear_pending_msg_events()[0] {
4214                         match update {
4215                                 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {},
4216                                 _ => panic!("Unexpected event"),
4217                         }
4218                 } else {
4219                         panic!("Unexpected event");
4220                 }
4221         } else {
4222                 expect_payment_failed!(nodes[1], second_payment_hash, true);
4223         }
4224 }
4225
4226 #[test]
4227 fn test_holding_cell_htlc_add_timeouts() {
4228         do_test_holding_cell_htlc_add_timeouts(false);
4229         do_test_holding_cell_htlc_add_timeouts(true);
4230 }
4231
4232 #[test]
4233 fn test_invalid_channel_announcement() {
4234         //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
4235         let secp_ctx = Secp256k1::new();
4236         let chanmon_cfgs = create_chanmon_cfgs(2);
4237         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4238         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4239         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4240
4241         let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
4242
4243         let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
4244         let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
4245         let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4246         let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4247
4248         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 } );
4249
4250         let as_bitcoin_key = as_chan.get_keys().inner.holder_channel_pubkeys.funding_pubkey;
4251         let bs_bitcoin_key = bs_chan.get_keys().inner.holder_channel_pubkeys.funding_pubkey;
4252
4253         let as_network_key = nodes[0].node.get_our_node_id();
4254         let bs_network_key = nodes[1].node.get_our_node_id();
4255
4256         let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
4257
4258         let mut chan_announcement;
4259
4260         macro_rules! dummy_unsigned_msg {
4261                 () => {
4262                         msgs::UnsignedChannelAnnouncement {
4263                                 features: ChannelFeatures::known(),
4264                                 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4265                                 short_channel_id: as_chan.get_short_channel_id().unwrap(),
4266                                 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
4267                                 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
4268                                 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
4269                                 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
4270                                 excess_data: Vec::new(),
4271                         };
4272                 }
4273         }
4274
4275         macro_rules! sign_msg {
4276                 ($unsigned_msg: expr) => {
4277                         let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
4278                         let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_keys().inner.funding_key);
4279                         let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_keys().inner.funding_key);
4280                         let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
4281                         let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
4282                         chan_announcement = msgs::ChannelAnnouncement {
4283                                 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
4284                                 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
4285                                 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
4286                                 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
4287                                 contents: $unsigned_msg
4288                         }
4289                 }
4290         }
4291
4292         let unsigned_msg = dummy_unsigned_msg!();
4293         sign_msg!(unsigned_msg);
4294         assert_eq!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap(), true);
4295         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 } );
4296
4297         // Configured with Network::Testnet
4298         let mut unsigned_msg = dummy_unsigned_msg!();
4299         unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.block_hash();
4300         sign_msg!(unsigned_msg);
4301         assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4302
4303         let mut unsigned_msg = dummy_unsigned_msg!();
4304         unsigned_msg.chain_hash = BlockHash::hash(&[1,2,3,4,5,6,7,8,9]);
4305         sign_msg!(unsigned_msg);
4306         assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4307 }
4308
4309 #[test]
4310 fn test_no_txn_manager_serialize_deserialize() {
4311         let chanmon_cfgs = create_chanmon_cfgs(2);
4312         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4313         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4314         let logger: test_utils::TestLogger;
4315         let fee_estimator: test_utils::TestFeeEstimator;
4316         let new_chan_monitor: test_utils::TestChannelMonitor;
4317         let keys_manager: test_utils::TestKeysInterface;
4318         let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4319         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4320
4321         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4322
4323         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4324
4325         let nodes_0_serialized = nodes[0].node.encode();
4326         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4327         nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
4328
4329         logger = test_utils::TestLogger::new();
4330         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4331         new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator);
4332         nodes[0].chan_monitor = &new_chan_monitor;
4333         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4334         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read).unwrap();
4335         assert!(chan_0_monitor_read.is_empty());
4336
4337         let mut nodes_0_read = &nodes_0_serialized[..];
4338         let config = UserConfig::default();
4339         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4340         let (_, nodes_0_deserialized_tmp) = {
4341                 let mut channel_monitors = HashMap::new();
4342                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4343                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4344                         default_config: config,
4345                         keys_manager: &keys_manager,
4346                         fee_estimator: &fee_estimator,
4347                         monitor: nodes[0].chan_monitor,
4348                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4349                         logger: &logger,
4350                         channel_monitors,
4351                 }).unwrap()
4352         };
4353         nodes_0_deserialized = nodes_0_deserialized_tmp;
4354         assert!(nodes_0_read.is_empty());
4355
4356         assert!(nodes[0].chan_monitor.add_monitor(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4357         nodes[0].node = &nodes_0_deserialized;
4358         nodes[0].block_notifier.register_listener(nodes[0].node);
4359         assert_eq!(nodes[0].node.list_channels().len(), 1);
4360         check_added_monitors!(nodes[0], 1);
4361
4362         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4363         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4364         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4365         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4366
4367         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4368         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4369         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4370         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4371
4372         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4373         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4374         for node in nodes.iter() {
4375                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4376                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4377                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4378         }
4379
4380         send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4381 }
4382
4383 #[test]
4384 fn test_manager_serialize_deserialize_events() {
4385         // This test makes sure the events field in ChannelManager survives de/serialization
4386         let chanmon_cfgs = create_chanmon_cfgs(2);
4387         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4388         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4389         let fee_estimator: test_utils::TestFeeEstimator;
4390         let logger: test_utils::TestLogger;
4391         let new_chan_monitor: test_utils::TestChannelMonitor;
4392         let keys_manager: test_utils::TestKeysInterface;
4393         let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4394         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4395
4396         // Start creating a channel, but stop right before broadcasting the event message FundingBroadcastSafe
4397         let channel_value = 100000;
4398         let push_msat = 10001;
4399         let a_flags = InitFeatures::known();
4400         let b_flags = InitFeatures::known();
4401         let node_a = nodes.pop().unwrap();
4402         let node_b = nodes.pop().unwrap();
4403         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4404         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()));
4405         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()));
4406
4407         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4408
4409         node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
4410         check_added_monitors!(node_a, 0);
4411
4412         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()));
4413         {
4414                 let mut added_monitors = node_b.chan_monitor.added_monitors.lock().unwrap();
4415                 assert_eq!(added_monitors.len(), 1);
4416                 assert_eq!(added_monitors[0].0, funding_output);
4417                 added_monitors.clear();
4418         }
4419
4420         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()));
4421         {
4422                 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
4423                 assert_eq!(added_monitors.len(), 1);
4424                 assert_eq!(added_monitors[0].0, funding_output);
4425                 added_monitors.clear();
4426         }
4427         // Normally, this is where node_a would check for a FundingBroadcastSafe event, but the test de/serializes first instead
4428
4429         nodes.push(node_a);
4430         nodes.push(node_b);
4431
4432         // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4433         let nodes_0_serialized = nodes[0].node.encode();
4434         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4435         nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
4436
4437         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4438         logger = test_utils::TestLogger::new();
4439         new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator);
4440         nodes[0].chan_monitor = &new_chan_monitor;
4441         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4442         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read).unwrap();
4443         assert!(chan_0_monitor_read.is_empty());
4444
4445         let mut nodes_0_read = &nodes_0_serialized[..];
4446         let config = UserConfig::default();
4447         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4448         let (_, nodes_0_deserialized_tmp) = {
4449                 let mut channel_monitors = HashMap::new();
4450                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4451                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4452                         default_config: config,
4453                         keys_manager: &keys_manager,
4454                         fee_estimator: &fee_estimator,
4455                         monitor: nodes[0].chan_monitor,
4456                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4457                         logger: &logger,
4458                         channel_monitors,
4459                 }).unwrap()
4460         };
4461         nodes_0_deserialized = nodes_0_deserialized_tmp;
4462         assert!(nodes_0_read.is_empty());
4463
4464         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4465
4466         assert!(nodes[0].chan_monitor.add_monitor(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4467         nodes[0].node = &nodes_0_deserialized;
4468
4469         // After deserializing, make sure the FundingBroadcastSafe event is still held by the channel manager
4470         let events_4 = nodes[0].node.get_and_clear_pending_events();
4471         assert_eq!(events_4.len(), 1);
4472         match events_4[0] {
4473                 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
4474                         assert_eq!(user_channel_id, 42);
4475                         assert_eq!(*funding_txo, funding_output);
4476                 },
4477                 _ => panic!("Unexpected event"),
4478         };
4479
4480         // Make sure the channel is functioning as though the de/serialization never happened
4481         nodes[0].block_notifier.register_listener(nodes[0].node);
4482         assert_eq!(nodes[0].node.list_channels().len(), 1);
4483         check_added_monitors!(nodes[0], 1);
4484
4485         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4486         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4487         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4488         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4489
4490         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4491         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4492         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4493         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4494
4495         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4496         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4497         for node in nodes.iter() {
4498                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4499                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4500                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4501         }
4502
4503         send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4504 }
4505
4506 #[test]
4507 fn test_simple_manager_serialize_deserialize() {
4508         let chanmon_cfgs = create_chanmon_cfgs(2);
4509         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4510         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4511         let logger: test_utils::TestLogger;
4512         let fee_estimator: test_utils::TestFeeEstimator;
4513         let new_chan_monitor: test_utils::TestChannelMonitor;
4514         let keys_manager: test_utils::TestKeysInterface;
4515         let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4516         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4517         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4518
4519         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4520         let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4521
4522         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4523
4524         let nodes_0_serialized = nodes[0].node.encode();
4525         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4526         nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
4527
4528         logger = test_utils::TestLogger::new();
4529         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4530         new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator);
4531         nodes[0].chan_monitor = &new_chan_monitor;
4532         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4533         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read).unwrap();
4534         assert!(chan_0_monitor_read.is_empty());
4535
4536         let mut nodes_0_read = &nodes_0_serialized[..];
4537         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4538         let (_, nodes_0_deserialized_tmp) = {
4539                 let mut channel_monitors = HashMap::new();
4540                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4541                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4542                         default_config: UserConfig::default(),
4543                         keys_manager: &keys_manager,
4544                         fee_estimator: &fee_estimator,
4545                         monitor: nodes[0].chan_monitor,
4546                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4547                         logger: &logger,
4548                         channel_monitors,
4549                 }).unwrap()
4550         };
4551         nodes_0_deserialized = nodes_0_deserialized_tmp;
4552         assert!(nodes_0_read.is_empty());
4553
4554         assert!(nodes[0].chan_monitor.add_monitor(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4555         nodes[0].node = &nodes_0_deserialized;
4556         check_added_monitors!(nodes[0], 1);
4557
4558         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4559
4560         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4561         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage, 1_000_000);
4562 }
4563
4564 #[test]
4565 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4566         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4567         let chanmon_cfgs = create_chanmon_cfgs(4);
4568         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4569         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4570         let logger: test_utils::TestLogger;
4571         let fee_estimator: test_utils::TestFeeEstimator;
4572         let new_chan_monitor: test_utils::TestChannelMonitor;
4573         let keys_manager: test_utils::TestKeysInterface;
4574         let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4575         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4576         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4577         create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known());
4578         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4579
4580         let mut node_0_stale_monitors_serialized = Vec::new();
4581         for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
4582                 let mut writer = test_utils::TestVecWriter(Vec::new());
4583                 monitor.1.write_for_disk(&mut writer).unwrap();
4584                 node_0_stale_monitors_serialized.push(writer.0);
4585         }
4586
4587         let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4588
4589         // Serialize the ChannelManager here, but the monitor we keep up-to-date
4590         let nodes_0_serialized = nodes[0].node.encode();
4591
4592         route_payment(&nodes[0], &[&nodes[3]], 1000000);
4593         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4594         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4595         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4596
4597         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4598         // nodes[3])
4599         let mut node_0_monitors_serialized = Vec::new();
4600         for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
4601                 let mut writer = test_utils::TestVecWriter(Vec::new());
4602                 monitor.1.write_for_disk(&mut writer).unwrap();
4603                 node_0_monitors_serialized.push(writer.0);
4604         }
4605
4606         logger = test_utils::TestLogger::new();
4607         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4608         new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator);
4609         nodes[0].chan_monitor = &new_chan_monitor;
4610
4611         let mut node_0_stale_monitors = Vec::new();
4612         for serialized in node_0_stale_monitors_serialized.iter() {
4613                 let mut read = &serialized[..];
4614                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read).unwrap();
4615                 assert!(read.is_empty());
4616                 node_0_stale_monitors.push(monitor);
4617         }
4618
4619         let mut node_0_monitors = Vec::new();
4620         for serialized in node_0_monitors_serialized.iter() {
4621                 let mut read = &serialized[..];
4622                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read).unwrap();
4623                 assert!(read.is_empty());
4624                 node_0_monitors.push(monitor);
4625         }
4626
4627         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4628
4629         let mut nodes_0_read = &nodes_0_serialized[..];
4630         if let Err(msgs::DecodeError::InvalidValue) =
4631                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4632                 default_config: UserConfig::default(),
4633                 keys_manager: &keys_manager,
4634                 fee_estimator: &fee_estimator,
4635                 monitor: nodes[0].chan_monitor,
4636                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4637                 logger: &logger,
4638                 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4639         }) { } else {
4640                 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4641         };
4642
4643         let mut nodes_0_read = &nodes_0_serialized[..];
4644         let (_, nodes_0_deserialized_tmp) =
4645                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4646                 default_config: UserConfig::default(),
4647                 keys_manager: &keys_manager,
4648                 fee_estimator: &fee_estimator,
4649                 monitor: nodes[0].chan_monitor,
4650                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4651                 logger: &logger,
4652                 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4653         }).unwrap();
4654         nodes_0_deserialized = nodes_0_deserialized_tmp;
4655         assert!(nodes_0_read.is_empty());
4656
4657         { // Channel close should result in a commitment tx and an HTLC tx
4658                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4659                 assert_eq!(txn.len(), 2);
4660                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4661                 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
4662         }
4663
4664         for monitor in node_0_monitors.drain(..) {
4665                 assert!(nodes[0].chan_monitor.add_monitor(monitor.get_funding_txo().0, monitor).is_ok());
4666                 check_added_monitors!(nodes[0], 1);
4667         }
4668         nodes[0].node = &nodes_0_deserialized;
4669
4670         // nodes[1] and nodes[2] have no lost state with nodes[0]...
4671         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4672         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4673         //... and we can even still claim the payment!
4674         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage, 1_000_000);
4675
4676         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4677         let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4678         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4679         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4680         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4681         assert_eq!(msg_events.len(), 1);
4682         if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4683                 match action {
4684                         &ErrorAction::SendErrorMessage { ref msg } => {
4685                                 assert_eq!(msg.channel_id, channel_id);
4686                         },
4687                         _ => panic!("Unexpected event!"),
4688                 }
4689         }
4690 }
4691
4692 macro_rules! check_spendable_outputs {
4693         ($node: expr, $der_idx: expr, $keysinterface: expr, $chan_value: expr) => {
4694                 {
4695                         let events = $node.chan_monitor.simple_monitor.get_and_clear_pending_events();
4696                         let mut txn = Vec::new();
4697                         for event in events {
4698                                 match event {
4699                                         Event::SpendableOutputs { ref outputs } => {
4700                                                 for outp in outputs {
4701                                                         match *outp {
4702                                                                 SpendableOutputDescriptor::StaticOutputCounterpartyPayment { ref outpoint, ref output, ref key_derivation_params } => {
4703                                                                         let input = TxIn {
4704                                                                                 previous_output: outpoint.into_bitcoin_outpoint(),
4705                                                                                 script_sig: Script::new(),
4706                                                                                 sequence: 0,
4707                                                                                 witness: Vec::new(),
4708                                                                         };
4709                                                                         let outp = TxOut {
4710                                                                                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4711                                                                                 value: output.value,
4712                                                                         };
4713                                                                         let mut spend_tx = Transaction {
4714                                                                                 version: 2,
4715                                                                                 lock_time: 0,
4716                                                                                 input: vec![input],
4717                                                                                 output: vec![outp],
4718                                                                         };
4719                                                                         let secp_ctx = Secp256k1::new();
4720                                                                         let keys = $keysinterface.derive_channel_keys($chan_value, key_derivation_params.0, key_derivation_params.1);
4721                                                                         let remotepubkey = keys.pubkeys().payment_point;
4722                                                                         let witness_script = Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: remotepubkey}, Network::Testnet).script_pubkey();
4723                                                                         let sighash = Message::from_slice(&bip143::SigHashCache::new(&spend_tx).signature_hash(0, &witness_script, output.value, SigHashType::All)[..]).unwrap();
4724                                                                         let remotesig = secp_ctx.sign(&sighash, &keys.inner.payment_key);
4725                                                                         spend_tx.input[0].witness.push(remotesig.serialize_der().to_vec());
4726                                                                         spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4727                                                                         spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
4728                                                                         txn.push(spend_tx);
4729                                                                 },
4730                                                                 SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref per_commitment_point, ref to_self_delay, ref output, ref key_derivation_params, ref revocation_pubkey } => {
4731                                                                         let input = TxIn {
4732                                                                                 previous_output: outpoint.into_bitcoin_outpoint(),
4733                                                                                 script_sig: Script::new(),
4734                                                                                 sequence: *to_self_delay as u32,
4735                                                                                 witness: Vec::new(),
4736                                                                         };
4737                                                                         let outp = TxOut {
4738                                                                                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4739                                                                                 value: output.value,
4740                                                                         };
4741                                                                         let mut spend_tx = Transaction {
4742                                                                                 version: 2,
4743                                                                                 lock_time: 0,
4744                                                                                 input: vec![input],
4745                                                                                 output: vec![outp],
4746                                                                         };
4747                                                                         let secp_ctx = Secp256k1::new();
4748                                                                         let keys = $keysinterface.derive_channel_keys($chan_value, key_derivation_params.0, key_derivation_params.1);
4749                                                                         if let Ok(delayed_payment_key) = chan_utils::derive_private_key(&secp_ctx, &per_commitment_point, &keys.inner.delayed_payment_base_key) {
4750
4751                                                                                 let delayed_payment_pubkey = PublicKey::from_secret_key(&secp_ctx, &delayed_payment_key);
4752                                                                                 let witness_script = chan_utils::get_revokeable_redeemscript(revocation_pubkey, *to_self_delay, &delayed_payment_pubkey);
4753                                                                                 let sighash = Message::from_slice(&bip143::SigHashCache::new(&spend_tx).signature_hash(0, &witness_script, output.value, SigHashType::All)[..]).unwrap();
4754                                                                                 let local_delayedsig = secp_ctx.sign(&sighash, &delayed_payment_key);
4755                                                                                 spend_tx.input[0].witness.push(local_delayedsig.serialize_der().to_vec());
4756                                                                                 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4757                                                                                 spend_tx.input[0].witness.push(vec!()); //MINIMALIF
4758                                                                                 spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
4759                                                                         } else { panic!() }
4760                                                                         txn.push(spend_tx);
4761                                                                 },
4762                                                                 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
4763                                                                         let secp_ctx = Secp256k1::new();
4764                                                                         let input = TxIn {
4765                                                                                 previous_output: outpoint.into_bitcoin_outpoint(),
4766                                                                                 script_sig: Script::new(),
4767                                                                                 sequence: 0,
4768                                                                                 witness: Vec::new(),
4769                                                                         };
4770                                                                         let outp = TxOut {
4771                                                                                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4772                                                                                 value: output.value,
4773                                                                         };
4774                                                                         let mut spend_tx = Transaction {
4775                                                                                 version: 2,
4776                                                                                 lock_time: 0,
4777                                                                                 input: vec![input],
4778                                                                                 output: vec![outp.clone()],
4779                                                                         };
4780                                                                         let secret = {
4781                                                                                 match ExtendedPrivKey::new_master(Network::Testnet, &$node.node_seed) {
4782                                                                                         Ok(master_key) => {
4783                                                                                                 match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx).expect("key space exhausted")) {
4784                                                                                                         Ok(key) => key,
4785                                                                                                         Err(_) => panic!("Your RNG is busted"),
4786                                                                                                 }
4787                                                                                         }
4788                                                                                         Err(_) => panic!("Your rng is busted"),
4789                                                                                 }
4790                                                                         };
4791                                                                         let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
4792                                                                         let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
4793                                                                         let sighash = Message::from_slice(&bip143::SigHashCache::new(&spend_tx).signature_hash(0, &witness_script, output.value, SigHashType::All)[..]).unwrap();
4794                                                                         let sig = secp_ctx.sign(&sighash, &secret.private_key.key);
4795                                                                         spend_tx.input[0].witness.push(sig.serialize_der().to_vec());
4796                                                                         spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4797                                                                         spend_tx.input[0].witness.push(pubkey.key.serialize().to_vec());
4798                                                                         txn.push(spend_tx);
4799                                                                 },
4800                                                         }
4801                                                 }
4802                                         },
4803                                         _ => panic!("Unexpected event"),
4804                                 };
4805                         }
4806                         txn
4807                 }
4808         }
4809 }
4810
4811 #[test]
4812 fn test_claim_sizeable_push_msat() {
4813         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4814         let chanmon_cfgs = create_chanmon_cfgs(2);
4815         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4816         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4817         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4818
4819         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4820         nodes[1].node.force_close_channel(&chan.2);
4821         check_closed_broadcast!(nodes[1], false);
4822         check_added_monitors!(nodes[1], 1);
4823         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4824         assert_eq!(node_txn.len(), 1);
4825         check_spends!(node_txn[0], chan.3);
4826         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
4827
4828         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4829         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
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(), 1);
4834         check_spends!(spend_txn[0], node_txn[0]);
4835 }
4836
4837 #[test]
4838 fn test_claim_on_remote_sizeable_push_msat() {
4839         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4840         // to_remote output is encumbered by a P2WPKH
4841         let chanmon_cfgs = create_chanmon_cfgs(2);
4842         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4843         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4844         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4845
4846         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4847         nodes[0].node.force_close_channel(&chan.2);
4848         check_closed_broadcast!(nodes[0], false);
4849         check_added_monitors!(nodes[0], 1);
4850
4851         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4852         assert_eq!(node_txn.len(), 1);
4853         check_spends!(node_txn[0], chan.3);
4854         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
4855
4856         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4857         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4858         check_closed_broadcast!(nodes[1], false);
4859         check_added_monitors!(nodes[1], 1);
4860         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4861
4862         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4863         assert_eq!(spend_txn.len(), 2);
4864         assert_eq!(spend_txn[0], spend_txn[1]);
4865         check_spends!(spend_txn[0], node_txn[0]);
4866 }
4867
4868 #[test]
4869 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4870         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4871         // to_remote output is encumbered by a P2WPKH
4872
4873         let chanmon_cfgs = create_chanmon_cfgs(2);
4874         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4875         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4876         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4877
4878         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4879         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4880         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4881         assert_eq!(revoked_local_txn[0].input.len(), 1);
4882         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4883
4884         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4885         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4886         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
4887         check_closed_broadcast!(nodes[1], false);
4888         check_added_monitors!(nodes[1], 1);
4889
4890         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4891         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4892         nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4893         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4894
4895         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4896         assert_eq!(spend_txn.len(), 3);
4897         assert_eq!(spend_txn[0], spend_txn[1]); // to_remote output on revoked remote commitment_tx
4898         check_spends!(spend_txn[0], revoked_local_txn[0]);
4899         check_spends!(spend_txn[2], node_txn[0]);
4900 }
4901
4902 #[test]
4903 fn test_static_spendable_outputs_preimage_tx() {
4904         let chanmon_cfgs = create_chanmon_cfgs(2);
4905         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4906         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4907         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4908
4909         // Create some initial channels
4910         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4911
4912         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4913
4914         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4915         assert_eq!(commitment_tx[0].input.len(), 1);
4916         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4917
4918         // Settle A's commitment tx on B's chain
4919         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4920         assert!(nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000));
4921         check_added_monitors!(nodes[1], 1);
4922         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
4923         check_added_monitors!(nodes[1], 1);
4924         let events = nodes[1].node.get_and_clear_pending_msg_events();
4925         match events[0] {
4926                 MessageSendEvent::UpdateHTLCs { .. } => {},
4927                 _ => panic!("Unexpected event"),
4928         }
4929         match events[1] {
4930                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4931                 _ => panic!("Unexepected event"),
4932         }
4933
4934         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4935         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4936         assert_eq!(node_txn.len(), 3);
4937         check_spends!(node_txn[0], commitment_tx[0]);
4938         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4939         check_spends!(node_txn[1], chan_1.3);
4940         check_spends!(node_txn[2], node_txn[1]);
4941
4942         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4943         nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4944         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4945
4946         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4947         assert_eq!(spend_txn.len(), 1);
4948         check_spends!(spend_txn[0], node_txn[0]);
4949 }
4950
4951 #[test]
4952 fn test_static_spendable_outputs_timeout_tx() {
4953         let chanmon_cfgs = create_chanmon_cfgs(2);
4954         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4955         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4956         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4957
4958         // Create some initial channels
4959         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4960
4961         // Rebalance the network a bit by relaying one payment through all the channels ...
4962         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
4963
4964         let (_, our_payment_hash) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4965
4966         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4967         assert_eq!(commitment_tx[0].input.len(), 1);
4968         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4969
4970         // Settle A's commitment tx on B' chain
4971         let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
4972         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 0);
4973         check_added_monitors!(nodes[1], 1);
4974         let events = nodes[1].node.get_and_clear_pending_msg_events();
4975         match events[0] {
4976                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4977                 _ => panic!("Unexpected event"),
4978         }
4979
4980         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4981         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4982         assert_eq!(node_txn.len(), 3); // ChannelManager : 2 (local commitent tx + HTLC-timeout), ChannelMonitor: timeout tx
4983         check_spends!(node_txn[0],  commitment_tx[0].clone());
4984         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4985         check_spends!(node_txn[1], chan_1.3.clone());
4986         check_spends!(node_txn[2], node_txn[1]);
4987
4988         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4989         nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4990         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4991         expect_payment_failed!(nodes[1], our_payment_hash, true);
4992
4993         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4994         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote (*2), timeout_tx.output (*1)
4995         check_spends!(spend_txn[2], node_txn[0].clone());
4996 }
4997
4998 #[test]
4999 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
5000         let chanmon_cfgs = create_chanmon_cfgs(2);
5001         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5002         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5003         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5004
5005         // Create some initial channels
5006         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5007
5008         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5009         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5010         assert_eq!(revoked_local_txn[0].input.len(), 1);
5011         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5012
5013         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
5014
5015         let  header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5016         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
5017         check_closed_broadcast!(nodes[1], false);
5018         check_added_monitors!(nodes[1], 1);
5019
5020         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5021         assert_eq!(node_txn.len(), 2);
5022         assert_eq!(node_txn[0].input.len(), 2);
5023         check_spends!(node_txn[0], revoked_local_txn[0]);
5024
5025         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5026         nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
5027         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5028
5029         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5030         assert_eq!(spend_txn.len(), 1);
5031         check_spends!(spend_txn[0], node_txn[0]);
5032 }
5033
5034 #[test]
5035 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
5036         let chanmon_cfgs = create_chanmon_cfgs(2);
5037         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5038         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5039         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5040
5041         // Create some initial channels
5042         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5043
5044         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5045         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5046         assert_eq!(revoked_local_txn[0].input.len(), 1);
5047         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5048
5049         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
5050
5051         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5052         // A will generate HTLC-Timeout from revoked commitment tx
5053         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5054         check_closed_broadcast!(nodes[0], false);
5055         check_added_monitors!(nodes[0], 1);
5056
5057         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5058         assert_eq!(revoked_htlc_txn.len(), 2);
5059         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5060         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5061         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5062         check_spends!(revoked_htlc_txn[1], chan_1.3);
5063
5064         // B will generate justice tx from A's revoked commitment/HTLC tx
5065         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 0);
5066         check_closed_broadcast!(nodes[1], false);
5067         check_added_monitors!(nodes[1], 1);
5068
5069         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5070         assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
5071         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5072         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5073         // transactions next...
5074         assert_eq!(node_txn[0].input.len(), 3);
5075         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5076
5077         assert_eq!(node_txn[1].input.len(), 2);
5078         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
5079         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5080                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5081         } else {
5082                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5083                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5084         }
5085
5086         assert_eq!(node_txn[2].input.len(), 1);
5087         check_spends!(node_txn[2], chan_1.3);
5088
5089         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5090         nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[1].clone()] }, 1);
5091         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5092
5093         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
5094         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5095         assert_eq!(spend_txn.len(), 1);
5096         assert_eq!(spend_txn[0].input.len(), 1);
5097         check_spends!(spend_txn[0], node_txn[1]);
5098 }
5099
5100 #[test]
5101 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
5102         let chanmon_cfgs = create_chanmon_cfgs(2);
5103         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5104         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5105         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5106
5107         // Create some initial channels
5108         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5109
5110         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5111         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5112         assert_eq!(revoked_local_txn[0].input.len(), 1);
5113         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5114
5115         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
5116         assert_eq!(revoked_local_txn[0].output.len(), 2);
5117
5118         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
5119
5120         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5121         // B will generate HTLC-Success from revoked commitment tx
5122         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5123         check_closed_broadcast!(nodes[1], false);
5124         check_added_monitors!(nodes[1], 1);
5125         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5126
5127         assert_eq!(revoked_htlc_txn.len(), 2);
5128         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5129         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5130         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5131
5132         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5133         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5134         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5135
5136         // A will generate justice tx from B's revoked commitment/HTLC tx
5137         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
5138         check_closed_broadcast!(nodes[0], false);
5139         check_added_monitors!(nodes[0], 1);
5140
5141         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5142         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5143
5144         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5145         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5146         // transactions next...
5147         assert_eq!(node_txn[0].input.len(), 2);
5148         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5149         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5150                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5151         } else {
5152                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5153                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5154         }
5155
5156         assert_eq!(node_txn[1].input.len(), 1);
5157         check_spends!(node_txn[1], revoked_htlc_txn[0]);
5158
5159         check_spends!(node_txn[2], chan_1.3);
5160
5161         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5162         nodes[0].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[1].clone()] }, 1);
5163         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5164
5165         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5166         // didn't try to generate any new transactions.
5167
5168         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5169         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5170         assert_eq!(spend_txn.len(), 3); // Duplicated SpendableOutput due to block rescan after revoked htlc output tracking
5171         assert_eq!(spend_txn[0], spend_txn[1]);
5172         assert_eq!(spend_txn[0].input.len(), 1);
5173         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5174         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5175         check_spends!(spend_txn[2], node_txn[1]); // spending justice tx output on the htlc success tx
5176 }
5177
5178 #[test]
5179 fn test_onchain_to_onchain_claim() {
5180         // Test that in case of channel closure, we detect the state of output thanks to
5181         // ChainWatchInterface and claim HTLC on downstream peer's remote commitment tx.
5182         // First, have C claim an HTLC against its own latest commitment transaction.
5183         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5184         // channel.
5185         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5186         // gets broadcast.
5187
5188         let chanmon_cfgs = create_chanmon_cfgs(3);
5189         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5190         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5191         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5192
5193         // Create some initial channels
5194         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5195         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5196
5197         // Rebalance the network a bit by relaying one payment through all the channels ...
5198         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5199         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5200
5201         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5202         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5203         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5204         check_spends!(commitment_tx[0], chan_2.3);
5205         nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000);
5206         check_added_monitors!(nodes[2], 1);
5207         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5208         assert!(updates.update_add_htlcs.is_empty());
5209         assert!(updates.update_fail_htlcs.is_empty());
5210         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5211         assert!(updates.update_fail_malformed_htlcs.is_empty());
5212
5213         nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
5214         check_closed_broadcast!(nodes[2], false);
5215         check_added_monitors!(nodes[2], 1);
5216
5217         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5218         assert_eq!(c_txn.len(), 3);
5219         assert_eq!(c_txn[0], c_txn[2]);
5220         assert_eq!(commitment_tx[0], c_txn[1]);
5221         check_spends!(c_txn[1], chan_2.3);
5222         check_spends!(c_txn[2], c_txn[1]);
5223         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5224         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5225         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5226         assert_eq!(c_txn[0].lock_time, 0); // Success tx
5227
5228         // So we broadcast C's commitment tx and HTLC-Success on B's chain, we should successfully be able to extract preimage and update downstream monitor
5229         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
5230         {
5231                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5232                 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-timeout tx
5233                 assert_eq!(b_txn.len(), 3);
5234                 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
5235                 check_spends!(b_txn[2], b_txn[1]); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
5236                 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5237                 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5238                 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5239                 check_spends!(b_txn[0], c_txn[1]); // timeout tx on C remote commitment tx, issued by ChannelMonitor, * 2 due to block rescan
5240                 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5241                 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5242                 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5243                 b_txn.clear();
5244         }
5245         check_added_monitors!(nodes[1], 1);
5246         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5247         check_added_monitors!(nodes[1], 1);
5248         match msg_events[0] {
5249                 MessageSendEvent::BroadcastChannelUpdate {  .. } => {},
5250                 _ => panic!("Unexpected event"),
5251         }
5252         match msg_events[1] {
5253                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
5254                         assert!(update_add_htlcs.is_empty());
5255                         assert!(update_fail_htlcs.is_empty());
5256                         assert_eq!(update_fulfill_htlcs.len(), 1);
5257                         assert!(update_fail_malformed_htlcs.is_empty());
5258                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5259                 },
5260                 _ => panic!("Unexpected event"),
5261         };
5262         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5263         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5264         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
5265         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5266         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5267         assert_eq!(b_txn.len(), 3);
5268         check_spends!(b_txn[1], chan_1.3);
5269         check_spends!(b_txn[2], b_txn[1]);
5270         check_spends!(b_txn[0], commitment_tx[0]);
5271         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5272         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5273         assert_eq!(b_txn[0].lock_time, 0); // Success tx
5274
5275         check_closed_broadcast!(nodes[1], false);
5276         check_added_monitors!(nodes[1], 1);
5277 }
5278
5279 #[test]
5280 fn test_duplicate_payment_hash_one_failure_one_success() {
5281         // Topology : A --> B --> C
5282         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5283         let chanmon_cfgs = create_chanmon_cfgs(3);
5284         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5285         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5286         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5287
5288         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5289         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5290
5291         let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5292         *nodes[0].network_payment_count.borrow_mut() -= 1;
5293         assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
5294
5295         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5296         assert_eq!(commitment_txn[0].input.len(), 1);
5297         check_spends!(commitment_txn[0], chan_2.3);
5298
5299         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5300         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
5301         check_closed_broadcast!(nodes[1], false);
5302         check_added_monitors!(nodes[1], 1);
5303
5304         let htlc_timeout_tx;
5305         { // Extract one of the two HTLC-Timeout transaction
5306                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5307                 // ChannelMonitor: timeout tx * 2, ChannelManager: local commitment tx + HTLC-timeout * 2
5308                 assert_eq!(node_txn.len(), 5);
5309                 check_spends!(node_txn[0], commitment_txn[0]);
5310                 assert_eq!(node_txn[0].input.len(), 1);
5311                 check_spends!(node_txn[1], commitment_txn[0]);
5312                 assert_eq!(node_txn[1].input.len(), 1);
5313                 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
5314                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5315                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5316                 check_spends!(node_txn[2], chan_2.3);
5317                 check_spends!(node_txn[3], node_txn[2]);
5318                 check_spends!(node_txn[4], node_txn[2]);
5319                 htlc_timeout_tx = node_txn[1].clone();
5320         }
5321
5322         nodes[2].node.claim_funds(our_payment_preimage, &None, 900_000);
5323         nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
5324         check_added_monitors!(nodes[2], 3);
5325         let events = nodes[2].node.get_and_clear_pending_msg_events();
5326         match events[0] {
5327                 MessageSendEvent::UpdateHTLCs { .. } => {},
5328                 _ => panic!("Unexpected event"),
5329         }
5330         match events[1] {
5331                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5332                 _ => panic!("Unexepected event"),
5333         }
5334         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5335         assert_eq!(htlc_success_txn.len(), 5); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs), ChannelManager: local commitment tx + HTLC-Success txn (*2 due to 2-HTLC outputs)
5336         check_spends!(htlc_success_txn[2], chan_2.3);
5337         check_spends!(htlc_success_txn[3], htlc_success_txn[2]);
5338         check_spends!(htlc_success_txn[4], htlc_success_txn[2]);
5339         assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
5340         assert_eq!(htlc_success_txn[0].input.len(), 1);
5341         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5342         assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
5343         assert_eq!(htlc_success_txn[1].input.len(), 1);
5344         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5345         assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
5346         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5347         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5348
5349         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![htlc_timeout_tx] }, 200);
5350         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 200, true, header.block_hash());
5351         expect_pending_htlcs_forwardable!(nodes[1]);
5352         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5353         assert!(htlc_updates.update_add_htlcs.is_empty());
5354         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5355         assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
5356         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5357         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5358         check_added_monitors!(nodes[1], 1);
5359
5360         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5361         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5362         {
5363                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5364                 let events = nodes[0].node.get_and_clear_pending_msg_events();
5365                 assert_eq!(events.len(), 1);
5366                 match events[0] {
5367                         MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. }  } => {
5368                         },
5369                         _ => { panic!("Unexpected event"); }
5370                 }
5371         }
5372         expect_payment_failed!(nodes[0], duplicate_payment_hash, false);
5373
5374         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5375         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
5376         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5377         assert!(updates.update_add_htlcs.is_empty());
5378         assert!(updates.update_fail_htlcs.is_empty());
5379         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5380         assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
5381         assert!(updates.update_fail_malformed_htlcs.is_empty());
5382         check_added_monitors!(nodes[1], 1);
5383
5384         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5385         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5386
5387         let events = nodes[0].node.get_and_clear_pending_events();
5388         match events[0] {
5389                 Event::PaymentSent { ref payment_preimage } => {
5390                         assert_eq!(*payment_preimage, our_payment_preimage);
5391                 }
5392                 _ => panic!("Unexpected event"),
5393         }
5394 }
5395
5396 #[test]
5397 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5398         let chanmon_cfgs = create_chanmon_cfgs(2);
5399         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5400         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5401         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5402
5403         // Create some initial channels
5404         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5405
5406         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5407         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5408         assert_eq!(local_txn[0].input.len(), 1);
5409         check_spends!(local_txn[0], chan_1.3);
5410
5411         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5412         nodes[1].node.claim_funds(payment_preimage, &None, 9_000_000);
5413         check_added_monitors!(nodes[1], 1);
5414         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5415         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![local_txn[0].clone()] }, 1);
5416         check_added_monitors!(nodes[1], 1);
5417         let events = nodes[1].node.get_and_clear_pending_msg_events();
5418         match events[0] {
5419                 MessageSendEvent::UpdateHTLCs { .. } => {},
5420                 _ => panic!("Unexpected event"),
5421         }
5422         match events[1] {
5423                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5424                 _ => panic!("Unexepected event"),
5425         }
5426         let node_txn = {
5427                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5428                 assert_eq!(node_txn[0].input.len(), 1);
5429                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5430                 check_spends!(node_txn[0], local_txn[0]);
5431                 vec![node_txn[0].clone(), node_txn[2].clone()]
5432         };
5433
5434         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5435         nodes[1].block_notifier.block_connected(&Block { header: header_201, txdata: node_txn.clone() }, 201);
5436         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5437
5438         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5439         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5440         assert_eq!(spend_txn.len(), 2);
5441         check_spends!(spend_txn[0], node_txn[0]);
5442         check_spends!(spend_txn[1], node_txn[1]);
5443 }
5444
5445 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5446         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5447         // unrevoked commitment transaction.
5448         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5449         // a remote RAA before they could be failed backwards (and combinations thereof).
5450         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5451         // use the same payment hashes.
5452         // Thus, we use a six-node network:
5453         //
5454         // A \         / E
5455         //    - C - D -
5456         // B /         \ F
5457         // And test where C fails back to A/B when D announces its latest commitment transaction
5458         let chanmon_cfgs = create_chanmon_cfgs(6);
5459         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5460         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
5461         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5462         let logger = test_utils::TestLogger::new();
5463
5464         create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5465         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5466         let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5467         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5468         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5469
5470         // Rebalance and check output sanity...
5471         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000, 500_000);
5472         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000, 500_000);
5473         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5474
5475         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5476         // 0th HTLC:
5477         let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], ds_dust_limit*1000); // not added < dust limit + HTLC tx fee
5478         // 1st HTLC:
5479         let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], ds_dust_limit*1000); // not added < dust limit + HTLC tx fee
5480         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
5481         let our_node_id = &nodes[1].node.get_our_node_id();
5482         let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV, &logger).unwrap();
5483         // 2nd HTLC:
5484         send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], ds_dust_limit*1000, payment_hash_1); // not added < dust limit + HTLC tx fee
5485         // 3rd HTLC:
5486         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], ds_dust_limit*1000, payment_hash_2); // not added < dust limit + HTLC tx fee
5487         // 4th HTLC:
5488         let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5489         // 5th HTLC:
5490         let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5491         let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
5492         // 6th HTLC:
5493         send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
5494         // 7th HTLC:
5495         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
5496
5497         // 8th HTLC:
5498         let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5499         // 9th HTLC:
5500         let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV, &logger).unwrap();
5501         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], ds_dust_limit*1000, payment_hash_5); // not added < dust limit + HTLC tx fee
5502
5503         // 10th HTLC:
5504         let (_, payment_hash_6) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], ds_dust_limit*1000); // not added < dust limit + HTLC tx fee
5505         // 11th HTLC:
5506         let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
5507         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
5508
5509         // Double-check that six of the new HTLC were added
5510         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5511         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5512         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5513         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5514
5515         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5516         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5517         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1, &None));
5518         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3, &None));
5519         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5, &None));
5520         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6, &None));
5521         check_added_monitors!(nodes[4], 0);
5522         expect_pending_htlcs_forwardable!(nodes[4]);
5523         check_added_monitors!(nodes[4], 1);
5524
5525         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5526         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5527         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5528         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5529         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5530         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5531
5532         // Fail 3rd below-dust and 7th above-dust HTLCs
5533         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2, &None));
5534         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4, &None));
5535         check_added_monitors!(nodes[5], 0);
5536         expect_pending_htlcs_forwardable!(nodes[5]);
5537         check_added_monitors!(nodes[5], 1);
5538
5539         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5540         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5541         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5542         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5543
5544         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5545
5546         expect_pending_htlcs_forwardable!(nodes[3]);
5547         check_added_monitors!(nodes[3], 1);
5548         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5549         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5550         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5551         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5552         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5553         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5554         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5555         if deliver_last_raa {
5556                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5557         } else {
5558                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5559         }
5560
5561         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5562         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5563         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5564         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5565         //
5566         // We now broadcast the latest commitment transaction, which *should* result in failures for
5567         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5568         // the non-broadcast above-dust HTLCs.
5569         //
5570         // Alternatively, we may broadcast the previous commitment transaction, which should only
5571         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5572         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5573
5574         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5575         if announce_latest {
5576                 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![ds_last_commitment_tx[0].clone()]}, 1);
5577         } else {
5578                 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![ds_prev_commitment_tx[0].clone()]}, 1);
5579         }
5580         connect_blocks(&nodes[2].block_notifier, ANTI_REORG_DELAY - 1, 1, true,  header.block_hash());
5581         check_closed_broadcast!(nodes[2], false);
5582         expect_pending_htlcs_forwardable!(nodes[2]);
5583         check_added_monitors!(nodes[2], 3);
5584
5585         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5586         assert_eq!(cs_msgs.len(), 2);
5587         let mut a_done = false;
5588         for msg in cs_msgs {
5589                 match msg {
5590                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5591                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5592                                 // should be failed-backwards here.
5593                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5594                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5595                                         for htlc in &updates.update_fail_htlcs {
5596                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 6 || if announce_latest { htlc.htlc_id == 3 || htlc.htlc_id == 5 } else { false });
5597                                         }
5598                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5599                                         assert!(!a_done);
5600                                         a_done = true;
5601                                         &nodes[0]
5602                                 } else {
5603                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5604                                         for htlc in &updates.update_fail_htlcs {
5605                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5606                                         }
5607                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5608                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5609                                         &nodes[1]
5610                                 };
5611                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5612                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5613                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5614                                 if announce_latest {
5615                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5616                                         if *node_id == nodes[0].node.get_our_node_id() {
5617                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5618                                         }
5619                                 }
5620                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5621                         },
5622                         _ => panic!("Unexpected event"),
5623                 }
5624         }
5625
5626         let as_events = nodes[0].node.get_and_clear_pending_events();
5627         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5628         let mut as_failds = HashSet::new();
5629         for event in as_events.iter() {
5630                 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5631                         assert!(as_failds.insert(*payment_hash));
5632                         if *payment_hash != payment_hash_2 {
5633                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5634                         } else {
5635                                 assert!(!rejected_by_dest);
5636                         }
5637                 } else { panic!("Unexpected event"); }
5638         }
5639         assert!(as_failds.contains(&payment_hash_1));
5640         assert!(as_failds.contains(&payment_hash_2));
5641         if announce_latest {
5642                 assert!(as_failds.contains(&payment_hash_3));
5643                 assert!(as_failds.contains(&payment_hash_5));
5644         }
5645         assert!(as_failds.contains(&payment_hash_6));
5646
5647         let bs_events = nodes[1].node.get_and_clear_pending_events();
5648         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5649         let mut bs_failds = HashSet::new();
5650         for event in bs_events.iter() {
5651                 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5652                         assert!(bs_failds.insert(*payment_hash));
5653                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5654                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5655                         } else {
5656                                 assert!(!rejected_by_dest);
5657                         }
5658                 } else { panic!("Unexpected event"); }
5659         }
5660         assert!(bs_failds.contains(&payment_hash_1));
5661         assert!(bs_failds.contains(&payment_hash_2));
5662         if announce_latest {
5663                 assert!(bs_failds.contains(&payment_hash_4));
5664         }
5665         assert!(bs_failds.contains(&payment_hash_5));
5666
5667         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5668         // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
5669         // to unknown-preimage-etc, B should have gotten 2. Thus, in the
5670         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
5671         // PaymentFailureNetworkUpdates.
5672         let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
5673         assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5674         let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5675         assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5676         for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
5677                 match event {
5678                         &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
5679                         _ => panic!("Unexpected event"),
5680                 }
5681         }
5682 }
5683
5684 #[test]
5685 fn test_fail_backwards_latest_remote_announce_a() {
5686         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5687 }
5688
5689 #[test]
5690 fn test_fail_backwards_latest_remote_announce_b() {
5691         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5692 }
5693
5694 #[test]
5695 fn test_fail_backwards_previous_remote_announce() {
5696         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5697         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5698         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5699 }
5700
5701 #[test]
5702 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5703         let chanmon_cfgs = create_chanmon_cfgs(2);
5704         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5705         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5706         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5707
5708         // Create some initial channels
5709         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5710
5711         let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5712         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5713         assert_eq!(local_txn[0].input.len(), 1);
5714         check_spends!(local_txn[0], chan_1.3);
5715
5716         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5717         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5718         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![local_txn[0].clone()] }, 200);
5719         check_closed_broadcast!(nodes[0], false);
5720         check_added_monitors!(nodes[0], 1);
5721
5722         let htlc_timeout = {
5723                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5724                 assert_eq!(node_txn[0].input.len(), 1);
5725                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5726                 check_spends!(node_txn[0], local_txn[0]);
5727                 node_txn[0].clone()
5728         };
5729
5730         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5731         nodes[0].block_notifier.block_connected(&Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
5732         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5733         expect_payment_failed!(nodes[0], our_payment_hash, true);
5734
5735         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5736         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5737         assert_eq!(spend_txn.len(), 3);
5738         assert_eq!(spend_txn[0], spend_txn[1]);
5739         check_spends!(spend_txn[0], local_txn[0]);
5740         check_spends!(spend_txn[2], htlc_timeout);
5741 }
5742
5743 #[test]
5744 fn test_key_derivation_params() {
5745         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5746         // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5747         // let us re-derive the channel key set to then derive a delayed_payment_key.
5748
5749         let chanmon_cfgs = create_chanmon_cfgs(3);
5750
5751         // We manually create the node configuration to backup the seed.
5752         let seed = [42; 32];
5753         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5754         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);
5755         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 };
5756         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5757         node_cfgs.remove(0);
5758         node_cfgs.insert(0, node);
5759
5760         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5761         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5762
5763         // Create some initial channels
5764         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5765         // for node 0
5766         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5767         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5768         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5769
5770         let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5771         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5772         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5773         assert_eq!(local_txn_1[0].input.len(), 1);
5774         check_spends!(local_txn_1[0], chan_1.3);
5775
5776         // We check funding pubkey are unique
5777         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]));
5778         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]));
5779         if from_0_funding_key_0 == from_1_funding_key_0
5780             || from_0_funding_key_0 == from_1_funding_key_1
5781             || from_0_funding_key_1 == from_1_funding_key_0
5782             || from_0_funding_key_1 == from_1_funding_key_1 {
5783                 panic!("Funding pubkeys aren't unique");
5784         }
5785
5786         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5787         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5788         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![local_txn_1[0].clone()] }, 200);
5789         check_closed_broadcast!(nodes[0], false);
5790         check_added_monitors!(nodes[0], 1);
5791
5792         let htlc_timeout = {
5793                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5794                 assert_eq!(node_txn[0].input.len(), 1);
5795                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5796                 check_spends!(node_txn[0], local_txn_1[0]);
5797                 node_txn[0].clone()
5798         };
5799
5800         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5801         nodes[0].block_notifier.block_connected(&Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
5802         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5803         expect_payment_failed!(nodes[0], our_payment_hash, true);
5804
5805         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5806         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5807         let spend_txn = check_spendable_outputs!(nodes[0], 1, new_keys_manager, 100000);
5808         assert_eq!(spend_txn.len(), 3);
5809         assert_eq!(spend_txn[0], spend_txn[1]);
5810         check_spends!(spend_txn[0], local_txn_1[0]);
5811         check_spends!(spend_txn[2], htlc_timeout);
5812 }
5813
5814 #[test]
5815 fn test_static_output_closing_tx() {
5816         let chanmon_cfgs = create_chanmon_cfgs(2);
5817         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5818         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5819         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5820
5821         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5822
5823         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
5824         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5825
5826         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5827         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![closing_tx.clone()] }, 0);
5828         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
5829
5830         let spend_txn = check_spendable_outputs!(nodes[0], 2, node_cfgs[0].keys_manager, 100000);
5831         assert_eq!(spend_txn.len(), 1);
5832         check_spends!(spend_txn[0], closing_tx);
5833
5834         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![closing_tx.clone()] }, 0);
5835         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
5836
5837         let spend_txn = check_spendable_outputs!(nodes[1], 2, node_cfgs[1].keys_manager, 100000);
5838         assert_eq!(spend_txn.len(), 1);
5839         check_spends!(spend_txn[0], closing_tx);
5840 }
5841
5842 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5843         let chanmon_cfgs = create_chanmon_cfgs(2);
5844         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5845         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5846         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5847         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5848
5849         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5850
5851         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5852         // present in B's local commitment transaction, but none of A's commitment transactions.
5853         assert!(nodes[1].node.claim_funds(our_payment_preimage, &None, if use_dust { 50_000 } else { 3_000_000 }));
5854         check_added_monitors!(nodes[1], 1);
5855
5856         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5857         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5858         let events = nodes[0].node.get_and_clear_pending_events();
5859         assert_eq!(events.len(), 1);
5860         match events[0] {
5861                 Event::PaymentSent { payment_preimage } => {
5862                         assert_eq!(payment_preimage, our_payment_preimage);
5863                 },
5864                 _ => panic!("Unexpected event"),
5865         }
5866
5867         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5868         check_added_monitors!(nodes[0], 1);
5869         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5870         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5871         check_added_monitors!(nodes[1], 1);
5872
5873         let mut block = Block {
5874                 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5875                 txdata: vec![],
5876         };
5877         for i in 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + CHAN_CONFIRM_DEPTH + 1 {
5878                 nodes[1].block_notifier.block_connected(&block, i);
5879                 block.header.prev_blockhash = block.block_hash();
5880         }
5881         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5882         check_closed_broadcast!(nodes[1], false);
5883         check_added_monitors!(nodes[1], 1);
5884 }
5885
5886 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5887         let chanmon_cfgs = create_chanmon_cfgs(2);
5888         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5889         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5890         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5891         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5892         let logger = test_utils::TestLogger::new();
5893
5894         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5895         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5896         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();
5897         nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
5898         check_added_monitors!(nodes[0], 1);
5899
5900         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5901
5902         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5903         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5904         // to "time out" the HTLC.
5905
5906         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5907
5908         for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5909                 nodes[0].block_notifier.block_connected(&Block { header, txdata: Vec::new()}, i);
5910                 header.prev_blockhash = header.block_hash();
5911         }
5912         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5913         check_closed_broadcast!(nodes[0], false);
5914         check_added_monitors!(nodes[0], 1);
5915 }
5916
5917 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5918         let chanmon_cfgs = create_chanmon_cfgs(3);
5919         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5920         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5921         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5922         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5923
5924         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5925         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5926         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5927         // actually revoked.
5928         let htlc_value = if use_dust { 50000 } else { 3000000 };
5929         let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5930         assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash, &None));
5931         expect_pending_htlcs_forwardable!(nodes[1]);
5932         check_added_monitors!(nodes[1], 1);
5933
5934         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5935         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5936         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5937         check_added_monitors!(nodes[0], 1);
5938         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5939         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5940         check_added_monitors!(nodes[1], 1);
5941         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5942         check_added_monitors!(nodes[1], 1);
5943         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5944
5945         if check_revoke_no_close {
5946                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5947                 check_added_monitors!(nodes[0], 1);
5948         }
5949
5950         let mut block = Block {
5951                 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5952                 txdata: vec![],
5953         };
5954         for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5955                 nodes[0].block_notifier.block_connected(&block, i);
5956                 block.header.prev_blockhash = block.block_hash();
5957         }
5958         if !check_revoke_no_close {
5959                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5960                 check_closed_broadcast!(nodes[0], false);
5961                 check_added_monitors!(nodes[0], 1);
5962         } else {
5963                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5964         }
5965 }
5966
5967 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5968 // There are only a few cases to test here:
5969 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5970 //    broadcastable commitment transactions result in channel closure,
5971 //  * its included in an unrevoked-but-previous remote commitment transaction,
5972 //  * its included in the latest remote or local commitment transactions.
5973 // We test each of the three possible commitment transactions individually and use both dust and
5974 // non-dust HTLCs.
5975 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5976 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5977 // tested for at least one of the cases in other tests.
5978 #[test]
5979 fn htlc_claim_single_commitment_only_a() {
5980         do_htlc_claim_local_commitment_only(true);
5981         do_htlc_claim_local_commitment_only(false);
5982
5983         do_htlc_claim_current_remote_commitment_only(true);
5984         do_htlc_claim_current_remote_commitment_only(false);
5985 }
5986
5987 #[test]
5988 fn htlc_claim_single_commitment_only_b() {
5989         do_htlc_claim_previous_remote_commitment_only(true, false);
5990         do_htlc_claim_previous_remote_commitment_only(false, false);
5991         do_htlc_claim_previous_remote_commitment_only(true, true);
5992         do_htlc_claim_previous_remote_commitment_only(false, true);
5993 }
5994
5995 #[test]
5996 #[should_panic]
5997 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
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 nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6002         //Force duplicate channel ids
6003         for node in nodes.iter() {
6004                 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
6005         }
6006
6007         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
6008         let channel_value_satoshis=10000;
6009         let push_msat=10001;
6010         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6011         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6012         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6013
6014         //Create a second channel with a channel_id collision
6015         assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6016 }
6017
6018 #[test]
6019 fn bolt2_open_channel_sending_node_checks_part2() {
6020         let chanmon_cfgs = create_chanmon_cfgs(2);
6021         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6022         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6023         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6024
6025         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
6026         let channel_value_satoshis=2^24;
6027         let push_msat=10001;
6028         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6029
6030         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
6031         let channel_value_satoshis=10000;
6032         // Test when push_msat is equal to 1000 * funding_satoshis.
6033         let push_msat=1000*channel_value_satoshis+1;
6034         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6035
6036         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
6037         let channel_value_satoshis=10000;
6038         let push_msat=10001;
6039         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
6040         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6041         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
6042
6043         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
6044         // 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
6045         assert!(node0_to_1_send_open_channel.channel_flags<=1);
6046
6047         // 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.
6048         assert!(BREAKDOWN_TIMEOUT>0);
6049         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
6050
6051         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
6052         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
6053         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
6054
6055         // 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.
6056         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
6057         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
6058         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
6059         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
6060         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6061 }
6062
6063 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6064 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6065 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6066 // is no longer affordable once it's freed.
6067 #[test]
6068 fn test_fail_holding_cell_htlc_upon_free() {
6069         let chanmon_cfgs = create_chanmon_cfgs(2);
6070         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6071         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6072         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6073         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6074         let logger = test_utils::TestLogger::new();
6075
6076         // First nodes[0] generates an update_fee, setting the channel's
6077         // pending_update_fee.
6078         nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 20).unwrap();
6079         check_added_monitors!(nodes[0], 1);
6080
6081         let events = nodes[0].node.get_and_clear_pending_msg_events();
6082         assert_eq!(events.len(), 1);
6083         let (update_msg, commitment_signed) = match events[0] {
6084                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6085                         (update_fee.as_ref(), commitment_signed)
6086                 },
6087                 _ => panic!("Unexpected event"),
6088         };
6089
6090         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6091
6092         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6093         let channel_reserve = chan_stat.channel_reserve_msat;
6094         let feerate = get_feerate!(nodes[0], chan.2);
6095
6096         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6097         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6098         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1);
6099         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6100         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();
6101
6102         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6103         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6104         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6105         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6106
6107         // Flush the pending fee update.
6108         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6109         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6110         check_added_monitors!(nodes[1], 1);
6111         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6112         check_added_monitors!(nodes[0], 1);
6113
6114         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6115         // HTLC, but now that the fee has been raised the payment will now fail, causing
6116         // us to surface its failure to the user.
6117         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6118         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6119         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 1 HTLC updates".to_string(), 1);
6120         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);
6121         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6122
6123         // Check that the payment failed to be sent out.
6124         let events = nodes[0].node.get_and_clear_pending_events();
6125         assert_eq!(events.len(), 1);
6126         match &events[0] {
6127                 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6128                         assert_eq!(our_payment_hash.clone(), *payment_hash);
6129                         assert_eq!(*rejected_by_dest, false);
6130                         assert_eq!(*error_code, None);
6131                         assert_eq!(*error_data, None);
6132                 },
6133                 _ => panic!("Unexpected event"),
6134         }
6135 }
6136
6137 // Test that if multiple HTLCs are released from the holding cell and one is
6138 // valid but the other is no longer valid upon release, the valid HTLC can be
6139 // successfully completed while the other one fails as expected.
6140 #[test]
6141 fn test_free_and_fail_holding_cell_htlcs() {
6142         let chanmon_cfgs = create_chanmon_cfgs(2);
6143         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6144         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6145         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6146         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6147         let logger = test_utils::TestLogger::new();
6148
6149         // First nodes[0] generates an update_fee, setting the channel's
6150         // pending_update_fee.
6151         nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 200).unwrap();
6152         check_added_monitors!(nodes[0], 1);
6153
6154         let events = nodes[0].node.get_and_clear_pending_msg_events();
6155         assert_eq!(events.len(), 1);
6156         let (update_msg, commitment_signed) = match events[0] {
6157                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6158                         (update_fee.as_ref(), commitment_signed)
6159                 },
6160                 _ => panic!("Unexpected event"),
6161         };
6162
6163         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6164
6165         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6166         let channel_reserve = chan_stat.channel_reserve_msat;
6167         let feerate = get_feerate!(nodes[0], chan.2);
6168
6169         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6170         let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
6171         let amt_1 = 20000;
6172         let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
6173         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1) - amt_1;
6174         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6175         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();
6176         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();
6177
6178         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6179         nodes[0].node.send_payment(&route_1, payment_hash_1, &None).unwrap();
6180         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6181         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6182         nodes[0].node.send_payment(&route_2, payment_hash_2, &None).unwrap();
6183         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6184         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6185
6186         // Flush the pending fee update.
6187         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6188         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6189         check_added_monitors!(nodes[1], 1);
6190         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6191         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6192         check_added_monitors!(nodes[0], 2);
6193
6194         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6195         // but now that the fee has been raised the second payment will now fail, causing us
6196         // to surface its failure to the user. The first payment should succeed.
6197         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6198         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6199         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 2 HTLC updates".to_string(), 1);
6200         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);
6201         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6202
6203         // Check that the second payment failed to be sent out.
6204         let events = nodes[0].node.get_and_clear_pending_events();
6205         assert_eq!(events.len(), 1);
6206         match &events[0] {
6207                 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6208                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6209                         assert_eq!(*rejected_by_dest, false);
6210                         assert_eq!(*error_code, None);
6211                         assert_eq!(*error_data, None);
6212                 },
6213                 _ => panic!("Unexpected event"),
6214         }
6215
6216         // Complete the first payment and the RAA from the fee update.
6217         let (payment_event, send_raa_event) = {
6218                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6219                 assert_eq!(msgs.len(), 2);
6220                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6221         };
6222         let raa = match send_raa_event {
6223                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6224                 _ => panic!("Unexpected event"),
6225         };
6226         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6227         check_added_monitors!(nodes[1], 1);
6228         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6229         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6230         let events = nodes[1].node.get_and_clear_pending_events();
6231         assert_eq!(events.len(), 1);
6232         match events[0] {
6233                 Event::PendingHTLCsForwardable { .. } => {},
6234                 _ => panic!("Unexpected event"),
6235         }
6236         nodes[1].node.process_pending_htlc_forwards();
6237         let events = nodes[1].node.get_and_clear_pending_events();
6238         assert_eq!(events.len(), 1);
6239         match events[0] {
6240                 Event::PaymentReceived { .. } => {},
6241                 _ => panic!("Unexpected event"),
6242         }
6243         nodes[1].node.claim_funds(payment_preimage_1, &None, amt_1);
6244         check_added_monitors!(nodes[1], 1);
6245         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6246         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6247         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6248         let events = nodes[0].node.get_and_clear_pending_events();
6249         assert_eq!(events.len(), 1);
6250         match events[0] {
6251                 Event::PaymentSent { ref payment_preimage } => {
6252                         assert_eq!(*payment_preimage, payment_preimage_1);
6253                 }
6254                 _ => panic!("Unexpected event"),
6255         }
6256 }
6257
6258 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6259 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6260 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6261 // once it's freed.
6262 #[test]
6263 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6264         let chanmon_cfgs = create_chanmon_cfgs(3);
6265         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6266         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6267         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6268         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6269         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6270         let logger = test_utils::TestLogger::new();
6271
6272         // First nodes[1] generates an update_fee, setting the channel's
6273         // pending_update_fee.
6274         nodes[1].node.update_fee(chan_1_2.2, get_feerate!(nodes[1], chan_1_2.2) + 20).unwrap();
6275         check_added_monitors!(nodes[1], 1);
6276
6277         let events = nodes[1].node.get_and_clear_pending_msg_events();
6278         assert_eq!(events.len(), 1);
6279         let (update_msg, commitment_signed) = match events[0] {
6280                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6281                         (update_fee.as_ref(), commitment_signed)
6282                 },
6283                 _ => panic!("Unexpected event"),
6284         };
6285
6286         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6287
6288         let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6289         let channel_reserve = chan_stat.channel_reserve_msat;
6290         let feerate = get_feerate!(nodes[0], chan_0_1.2);
6291
6292         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6293         let feemsat = 239;
6294         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6295         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6296         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1) - total_routing_fee_msat;
6297         let payment_event = {
6298                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6299                 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();
6300                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6301                 check_added_monitors!(nodes[0], 1);
6302
6303                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6304                 assert_eq!(events.len(), 1);
6305
6306                 SendEvent::from_event(events.remove(0))
6307         };
6308         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6309         check_added_monitors!(nodes[1], 0);
6310         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6311         expect_pending_htlcs_forwardable!(nodes[1]);
6312
6313         chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6314         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6315
6316         // Flush the pending fee update.
6317         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6318         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6319         check_added_monitors!(nodes[2], 1);
6320         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6321         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6322         check_added_monitors!(nodes[1], 2);
6323
6324         // A final RAA message is generated to finalize the fee update.
6325         let events = nodes[1].node.get_and_clear_pending_msg_events();
6326         assert_eq!(events.len(), 1);
6327
6328         let raa_msg = match &events[0] {
6329                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6330                         msg.clone()
6331                 },
6332                 _ => panic!("Unexpected event"),
6333         };
6334
6335         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6336         check_added_monitors!(nodes[2], 1);
6337         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6338
6339         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6340         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6341         assert_eq!(process_htlc_forwards_event.len(), 1);
6342         match &process_htlc_forwards_event[0] {
6343                 &Event::PendingHTLCsForwardable { .. } => {},
6344                 _ => panic!("Unexpected event"),
6345         }
6346
6347         // In response, we call ChannelManager's process_pending_htlc_forwards
6348         nodes[1].node.process_pending_htlc_forwards();
6349         check_added_monitors!(nodes[1], 1);
6350
6351         // This causes the HTLC to be failed backwards.
6352         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6353         assert_eq!(fail_event.len(), 1);
6354         let (fail_msg, commitment_signed) = match &fail_event[0] {
6355                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6356                         assert_eq!(updates.update_add_htlcs.len(), 0);
6357                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6358                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6359                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6360                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6361                 },
6362                 _ => panic!("Unexpected event"),
6363         };
6364
6365         // Pass the failure messages back to nodes[0].
6366         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6367         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6368
6369         // Complete the HTLC failure+removal process.
6370         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6371         check_added_monitors!(nodes[0], 1);
6372         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6373         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6374         check_added_monitors!(nodes[1], 2);
6375         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6376         assert_eq!(final_raa_event.len(), 1);
6377         let raa = match &final_raa_event[0] {
6378                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6379                 _ => panic!("Unexpected event"),
6380         };
6381         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6382         let fail_msg_event = nodes[0].node.get_and_clear_pending_msg_events();
6383         assert_eq!(fail_msg_event.len(), 1);
6384         match &fail_msg_event[0] {
6385                 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6386                 _ => panic!("Unexpected event"),
6387         }
6388         let failure_event = nodes[0].node.get_and_clear_pending_events();
6389         assert_eq!(failure_event.len(), 1);
6390         match &failure_event[0] {
6391                 &Event::PaymentFailed { rejected_by_dest, .. } => {
6392                         assert!(!rejected_by_dest);
6393                 },
6394                 _ => panic!("Unexpected event"),
6395         }
6396         check_added_monitors!(nodes[0], 1);
6397 }
6398
6399 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6400 // 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.
6401 //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.
6402
6403 #[test]
6404 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6405         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6406         let chanmon_cfgs = create_chanmon_cfgs(2);
6407         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6408         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6409         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6410         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6411
6412         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6413         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6414         let logger = test_utils::TestLogger::new();
6415         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();
6416         route.paths[0][0].fee_msat = 100;
6417
6418         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6419                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6420         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6421         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6422 }
6423
6424 #[test]
6425 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6426         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6427         let chanmon_cfgs = create_chanmon_cfgs(2);
6428         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6429         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6430         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6431         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6432         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6433
6434         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6435         let logger = test_utils::TestLogger::new();
6436         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();
6437         route.paths[0][0].fee_msat = 0;
6438         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6439                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6440
6441         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6442         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6443 }
6444
6445 #[test]
6446 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6447         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6448         let chanmon_cfgs = create_chanmon_cfgs(2);
6449         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6450         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6451         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6452         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
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 logger = test_utils::TestLogger::new();
6457         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();
6458         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6459         check_added_monitors!(nodes[0], 1);
6460         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6461         updates.update_add_htlcs[0].amount_msat = 0;
6462
6463         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6464         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6465         check_closed_broadcast!(nodes[1], true).unwrap();
6466         check_added_monitors!(nodes[1], 1);
6467 }
6468
6469 #[test]
6470 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6471         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6472         //It is enforced when constructing a route.
6473         let chanmon_cfgs = create_chanmon_cfgs(2);
6474         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6475         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6476         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6477         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 0, InitFeatures::known(), InitFeatures::known());
6478         let logger = test_utils::TestLogger::new();
6479
6480         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6481
6482         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6483         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();
6484         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::RouteError { ref err },
6485                 assert_eq!(err, &"Channel CLTV overflowed?"));
6486 }
6487
6488 #[test]
6489 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6490         //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.
6491         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6492         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6493         let chanmon_cfgs = create_chanmon_cfgs(2);
6494         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6495         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6496         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6497         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6498         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6499
6500         let logger = test_utils::TestLogger::new();
6501         for i in 0..max_accepted_htlcs {
6502                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6503                 let payment_event = {
6504                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6505                         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();
6506                         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6507                         check_added_monitors!(nodes[0], 1);
6508
6509                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6510                         assert_eq!(events.len(), 1);
6511                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6512                                 assert_eq!(htlcs[0].htlc_id, i);
6513                         } else {
6514                                 assert!(false);
6515                         }
6516                         SendEvent::from_event(events.remove(0))
6517                 };
6518                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6519                 check_added_monitors!(nodes[1], 0);
6520                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6521
6522                 expect_pending_htlcs_forwardable!(nodes[1]);
6523                 expect_payment_received!(nodes[1], our_payment_hash, 100000);
6524         }
6525         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6526         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6527         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();
6528         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6529                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6530
6531         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6532         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6533 }
6534
6535 #[test]
6536 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6537         //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.
6538         let chanmon_cfgs = create_chanmon_cfgs(2);
6539         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6540         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6541         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6542         let channel_value = 100000;
6543         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6544         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6545
6546         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight, max_in_flight);
6547
6548         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6549         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6550         let logger = test_utils::TestLogger::new();
6551         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();
6552         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6553                 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)));
6554
6555         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6556         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);
6557
6558         send_payment(&nodes[0], &[&nodes[1]], max_in_flight, max_in_flight);
6559 }
6560
6561 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6562 #[test]
6563 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6564         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6565         let chanmon_cfgs = create_chanmon_cfgs(2);
6566         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6567         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6568         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6569         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6570         let htlc_minimum_msat: u64;
6571         {
6572                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6573                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6574                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6575         }
6576
6577         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6578         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6579         let logger = test_utils::TestLogger::new();
6580         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();
6581         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6582         check_added_monitors!(nodes[0], 1);
6583         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6584         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6585         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6586         assert!(nodes[1].node.list_channels().is_empty());
6587         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6588         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()));
6589         check_added_monitors!(nodes[1], 1);
6590 }
6591
6592 #[test]
6593 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6594         //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
6595         let chanmon_cfgs = create_chanmon_cfgs(2);
6596         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6597         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6598         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6599         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6600         let logger = test_utils::TestLogger::new();
6601
6602         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6603         let channel_reserve = chan_stat.channel_reserve_msat;
6604         let feerate = get_feerate!(nodes[0], chan.2);
6605         // The 2* and +1 are for the fee spike reserve.
6606         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1);
6607
6608         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6609         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6610         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6611         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();
6612         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6613         check_added_monitors!(nodes[0], 1);
6614         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6615
6616         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6617         // at this time channel-initiatee receivers are not required to enforce that senders
6618         // respect the fee_spike_reserve.
6619         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6620         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6621
6622         assert!(nodes[1].node.list_channels().is_empty());
6623         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6624         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6625         check_added_monitors!(nodes[1], 1);
6626 }
6627
6628 #[test]
6629 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6630         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6631         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6632         let chanmon_cfgs = create_chanmon_cfgs(2);
6633         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6634         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6635         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6636         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6637         let logger = test_utils::TestLogger::new();
6638
6639         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6640         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6641
6642         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6643         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();
6644
6645         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
6646         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6647         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &None, cur_height).unwrap();
6648         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6649
6650         let mut msg = msgs::UpdateAddHTLC {
6651                 channel_id: chan.2,
6652                 htlc_id: 0,
6653                 amount_msat: 1000,
6654                 payment_hash: our_payment_hash,
6655                 cltv_expiry: htlc_cltv,
6656                 onion_routing_packet: onion_packet.clone(),
6657         };
6658
6659         for i in 0..super::channel::OUR_MAX_HTLCS {
6660                 msg.htlc_id = i as u64;
6661                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6662         }
6663         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6664         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6665
6666         assert!(nodes[1].node.list_channels().is_empty());
6667         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6668         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6669         check_added_monitors!(nodes[1], 1);
6670 }
6671
6672 #[test]
6673 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6674         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6675         let chanmon_cfgs = create_chanmon_cfgs(2);
6676         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6677         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6678         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6679         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6680         let logger = test_utils::TestLogger::new();
6681
6682         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6683         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6684         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();
6685         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6686         check_added_monitors!(nodes[0], 1);
6687         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6688         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6689         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6690
6691         assert!(nodes[1].node.list_channels().is_empty());
6692         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6693         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6694         check_added_monitors!(nodes[1], 1);
6695 }
6696
6697 #[test]
6698 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6699         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6700         let chanmon_cfgs = create_chanmon_cfgs(2);
6701         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6702         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6703         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6704         let logger = test_utils::TestLogger::new();
6705
6706         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6707         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6708         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6709         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();
6710         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6711         check_added_monitors!(nodes[0], 1);
6712         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6713         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6714         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6715
6716         assert!(nodes[1].node.list_channels().is_empty());
6717         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6718         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6719         check_added_monitors!(nodes[1], 1);
6720 }
6721
6722 #[test]
6723 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6724         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6725         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6726         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6727         let chanmon_cfgs = create_chanmon_cfgs(2);
6728         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6729         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6730         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6731         let logger = test_utils::TestLogger::new();
6732
6733         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6734         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6735         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6736         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();
6737         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6738         check_added_monitors!(nodes[0], 1);
6739         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6740         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6741
6742         //Disconnect and Reconnect
6743         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6744         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6745         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6746         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6747         assert_eq!(reestablish_1.len(), 1);
6748         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6749         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6750         assert_eq!(reestablish_2.len(), 1);
6751         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6752         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6753         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6754         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6755
6756         //Resend HTLC
6757         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6758         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6759         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6760         check_added_monitors!(nodes[1], 1);
6761         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6762
6763         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6764
6765         assert!(nodes[1].node.list_channels().is_empty());
6766         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6767         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6768         check_added_monitors!(nodes[1], 1);
6769 }
6770
6771 #[test]
6772 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6773         //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.
6774
6775         let chanmon_cfgs = create_chanmon_cfgs(2);
6776         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6777         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6778         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6779         let logger = test_utils::TestLogger::new();
6780         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6781         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6782         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6783         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();
6784         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6785
6786         check_added_monitors!(nodes[0], 1);
6787         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6788         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6789
6790         let update_msg = msgs::UpdateFulfillHTLC{
6791                 channel_id: chan.2,
6792                 htlc_id: 0,
6793                 payment_preimage: our_payment_preimage,
6794         };
6795
6796         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6797
6798         assert!(nodes[0].node.list_channels().is_empty());
6799         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6800         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()));
6801         check_added_monitors!(nodes[0], 1);
6802 }
6803
6804 #[test]
6805 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6806         //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.
6807
6808         let chanmon_cfgs = create_chanmon_cfgs(2);
6809         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6810         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6811         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6812         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6813         let logger = test_utils::TestLogger::new();
6814
6815         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6816         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6817         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();
6818         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6819         check_added_monitors!(nodes[0], 1);
6820         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6821         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6822
6823         let update_msg = msgs::UpdateFailHTLC{
6824                 channel_id: chan.2,
6825                 htlc_id: 0,
6826                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6827         };
6828
6829         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6830
6831         assert!(nodes[0].node.list_channels().is_empty());
6832         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6833         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()));
6834         check_added_monitors!(nodes[0], 1);
6835 }
6836
6837 #[test]
6838 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6839         //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.
6840
6841         let chanmon_cfgs = create_chanmon_cfgs(2);
6842         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6843         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6844         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6845         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6846         let logger = test_utils::TestLogger::new();
6847
6848         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6849         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6850         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();
6851         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6852         check_added_monitors!(nodes[0], 1);
6853         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6854         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6855
6856         let update_msg = msgs::UpdateFailMalformedHTLC{
6857                 channel_id: chan.2,
6858                 htlc_id: 0,
6859                 sha256_of_onion: [1; 32],
6860                 failure_code: 0x8000,
6861         };
6862
6863         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6864
6865         assert!(nodes[0].node.list_channels().is_empty());
6866         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6867         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()));
6868         check_added_monitors!(nodes[0], 1);
6869 }
6870
6871 #[test]
6872 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6873         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6874
6875         let chanmon_cfgs = create_chanmon_cfgs(2);
6876         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6877         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6878         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6879         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6880
6881         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6882
6883         nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6884         check_added_monitors!(nodes[1], 1);
6885
6886         let events = nodes[1].node.get_and_clear_pending_msg_events();
6887         assert_eq!(events.len(), 1);
6888         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6889                 match events[0] {
6890                         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, .. } } => {
6891                                 assert!(update_add_htlcs.is_empty());
6892                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6893                                 assert!(update_fail_htlcs.is_empty());
6894                                 assert!(update_fail_malformed_htlcs.is_empty());
6895                                 assert!(update_fee.is_none());
6896                                 update_fulfill_htlcs[0].clone()
6897                         },
6898                         _ => panic!("Unexpected event"),
6899                 }
6900         };
6901
6902         update_fulfill_msg.htlc_id = 1;
6903
6904         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6905
6906         assert!(nodes[0].node.list_channels().is_empty());
6907         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6908         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6909         check_added_monitors!(nodes[0], 1);
6910 }
6911
6912 #[test]
6913 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6914         //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.
6915
6916         let chanmon_cfgs = create_chanmon_cfgs(2);
6917         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6918         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6919         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6920         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6921
6922         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6923
6924         nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6925         check_added_monitors!(nodes[1], 1);
6926
6927         let events = nodes[1].node.get_and_clear_pending_msg_events();
6928         assert_eq!(events.len(), 1);
6929         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6930                 match events[0] {
6931                         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, .. } } => {
6932                                 assert!(update_add_htlcs.is_empty());
6933                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6934                                 assert!(update_fail_htlcs.is_empty());
6935                                 assert!(update_fail_malformed_htlcs.is_empty());
6936                                 assert!(update_fee.is_none());
6937                                 update_fulfill_htlcs[0].clone()
6938                         },
6939                         _ => panic!("Unexpected event"),
6940                 }
6941         };
6942
6943         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6944
6945         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6946
6947         assert!(nodes[0].node.list_channels().is_empty());
6948         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6949         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6950         check_added_monitors!(nodes[0], 1);
6951 }
6952
6953 #[test]
6954 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6955         //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.
6956
6957         let chanmon_cfgs = create_chanmon_cfgs(2);
6958         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6959         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6960         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6961         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6962         let logger = test_utils::TestLogger::new();
6963
6964         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6965         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6966         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();
6967         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6968         check_added_monitors!(nodes[0], 1);
6969
6970         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6971         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6972
6973         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6974         check_added_monitors!(nodes[1], 0);
6975         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6976
6977         let events = nodes[1].node.get_and_clear_pending_msg_events();
6978
6979         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6980                 match events[0] {
6981                         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, .. } } => {
6982                                 assert!(update_add_htlcs.is_empty());
6983                                 assert!(update_fulfill_htlcs.is_empty());
6984                                 assert!(update_fail_htlcs.is_empty());
6985                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6986                                 assert!(update_fee.is_none());
6987                                 update_fail_malformed_htlcs[0].clone()
6988                         },
6989                         _ => panic!("Unexpected event"),
6990                 }
6991         };
6992         update_msg.failure_code &= !0x8000;
6993         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6994
6995         assert!(nodes[0].node.list_channels().is_empty());
6996         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6997         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6998         check_added_monitors!(nodes[0], 1);
6999 }
7000
7001 #[test]
7002 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
7003         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
7004         //    * 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.
7005
7006         let chanmon_cfgs = create_chanmon_cfgs(3);
7007         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7008         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7009         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7010         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7011         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7012         let logger = test_utils::TestLogger::new();
7013
7014         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
7015
7016         //First hop
7017         let mut payment_event = {
7018                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
7019                 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();
7020                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
7021                 check_added_monitors!(nodes[0], 1);
7022                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7023                 assert_eq!(events.len(), 1);
7024                 SendEvent::from_event(events.remove(0))
7025         };
7026         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7027         check_added_monitors!(nodes[1], 0);
7028         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7029         expect_pending_htlcs_forwardable!(nodes[1]);
7030         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7031         assert_eq!(events_2.len(), 1);
7032         check_added_monitors!(nodes[1], 1);
7033         payment_event = SendEvent::from_event(events_2.remove(0));
7034         assert_eq!(payment_event.msgs.len(), 1);
7035
7036         //Second Hop
7037         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7038         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7039         check_added_monitors!(nodes[2], 0);
7040         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7041
7042         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7043         assert_eq!(events_3.len(), 1);
7044         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
7045                 match events_3[0] {
7046                         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 } } => {
7047                                 assert!(update_add_htlcs.is_empty());
7048                                 assert!(update_fulfill_htlcs.is_empty());
7049                                 assert!(update_fail_htlcs.is_empty());
7050                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7051                                 assert!(update_fee.is_none());
7052                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
7053                         },
7054                         _ => panic!("Unexpected event"),
7055                 }
7056         };
7057
7058         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
7059
7060         check_added_monitors!(nodes[1], 0);
7061         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
7062         expect_pending_htlcs_forwardable!(nodes[1]);
7063         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7064         assert_eq!(events_4.len(), 1);
7065
7066         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7067         match events_4[0] {
7068                 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, .. } } => {
7069                         assert!(update_add_htlcs.is_empty());
7070                         assert!(update_fulfill_htlcs.is_empty());
7071                         assert_eq!(update_fail_htlcs.len(), 1);
7072                         assert!(update_fail_malformed_htlcs.is_empty());
7073                         assert!(update_fee.is_none());
7074                 },
7075                 _ => panic!("Unexpected event"),
7076         };
7077
7078         check_added_monitors!(nodes[1], 1);
7079 }
7080
7081 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7082         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7083         // 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
7084         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7085
7086         let chanmon_cfgs = create_chanmon_cfgs(2);
7087         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7088         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7089         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7090         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7091
7092         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7093
7094         // We route 2 dust-HTLCs between A and B
7095         let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7096         let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7097         route_payment(&nodes[0], &[&nodes[1]], 1000000);
7098
7099         // Cache one local commitment tx as previous
7100         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7101
7102         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7103         assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2, &None));
7104         check_added_monitors!(nodes[1], 0);
7105         expect_pending_htlcs_forwardable!(nodes[1]);
7106         check_added_monitors!(nodes[1], 1);
7107
7108         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7109         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7110         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7111         check_added_monitors!(nodes[0], 1);
7112
7113         // Cache one local commitment tx as lastest
7114         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7115
7116         let events = nodes[0].node.get_and_clear_pending_msg_events();
7117         match events[0] {
7118                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7119                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7120                 },
7121                 _ => panic!("Unexpected event"),
7122         }
7123         match events[1] {
7124                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7125                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7126                 },
7127                 _ => panic!("Unexpected event"),
7128         }
7129
7130         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7131         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7132         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7133
7134         if announce_latest {
7135                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_last_commitment_tx[0].clone()]}, 1);
7136         } else {
7137                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_prev_commitment_tx[0].clone()]}, 1);
7138         }
7139
7140         check_closed_broadcast!(nodes[0], false);
7141         check_added_monitors!(nodes[0], 1);
7142
7143         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7144         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 1, true,  header.block_hash());
7145         let events = nodes[0].node.get_and_clear_pending_events();
7146         // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
7147         assert_eq!(events.len(), 2);
7148         let mut first_failed = false;
7149         for event in events {
7150                 match event {
7151                         Event::PaymentFailed { payment_hash, .. } => {
7152                                 if payment_hash == payment_hash_1 {
7153                                         assert!(!first_failed);
7154                                         first_failed = true;
7155                                 } else {
7156                                         assert_eq!(payment_hash, payment_hash_2);
7157                                 }
7158                         }
7159                         _ => panic!("Unexpected event"),
7160                 }
7161         }
7162 }
7163
7164 #[test]
7165 fn test_failure_delay_dust_htlc_local_commitment() {
7166         do_test_failure_delay_dust_htlc_local_commitment(true);
7167         do_test_failure_delay_dust_htlc_local_commitment(false);
7168 }
7169
7170 #[test]
7171 fn test_no_failure_dust_htlc_local_commitment() {
7172         // Transaction filters for failing back dust htlc based on local commitment txn infos has been
7173         // prone to error, we test here that a dummy transaction don't fail them.
7174
7175         let chanmon_cfgs = create_chanmon_cfgs(2);
7176         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7177         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7178         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7179         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7180
7181         // Rebalance a bit
7182         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7183
7184         let as_dust_limit = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7185         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7186
7187         // We route 2 dust-HTLCs between A and B
7188         let (preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7189         let (preimage_2, _) = route_payment(&nodes[1], &[&nodes[0]], as_dust_limit*1000);
7190
7191         // Build a dummy invalid transaction trying to spend a commitment tx
7192         let input = TxIn {
7193                 previous_output: BitcoinOutPoint { txid: chan.3.txid(), vout: 0 },
7194                 script_sig: Script::new(),
7195                 sequence: 0,
7196                 witness: Vec::new(),
7197         };
7198
7199         let outp = TxOut {
7200                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
7201                 value: 10000,
7202         };
7203
7204         let dummy_tx = Transaction {
7205                 version: 2,
7206                 lock_time: 0,
7207                 input: vec![input],
7208                 output: vec![outp]
7209         };
7210
7211         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7212         nodes[0].chan_monitor.simple_monitor.block_connected(&header, &[(0, &dummy_tx)], 1);
7213         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7214         assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
7215         // We broadcast a few more block to check everything is all right
7216         connect_blocks(&nodes[0].block_notifier, 20, 1, true, header.block_hash());
7217         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7218         assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
7219
7220         claim_payment(&nodes[0], &vec!(&nodes[1])[..], preimage_1, bs_dust_limit*1000);
7221         claim_payment(&nodes[1], &vec!(&nodes[0])[..], preimage_2, as_dust_limit*1000);
7222 }
7223
7224 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7225         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7226         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7227         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7228         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7229         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7230         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7231
7232         let chanmon_cfgs = create_chanmon_cfgs(3);
7233         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7234         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7235         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7236         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7237
7238         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7239
7240         let (_payment_preimage_1, dust_hash) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7241         let (_payment_preimage_2, non_dust_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7242
7243         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7244         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7245
7246         // We revoked bs_commitment_tx
7247         if revoked {
7248                 let (payment_preimage_3, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7249                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 1_000_000);
7250         }
7251
7252         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7253         let mut timeout_tx = Vec::new();
7254         if local {
7255                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7256                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_commitment_tx[0].clone()]}, 1);
7257                 check_closed_broadcast!(nodes[0], false);
7258                 check_added_monitors!(nodes[0], 1);
7259                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7260                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7261                 let parent_hash  = connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 2, true, header.block_hash());
7262                 expect_payment_failed!(nodes[0], dust_hash, true);
7263                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7264                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7265                 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7266                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7267                 nodes[0].block_notifier.block_connected(&Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
7268                 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7269                 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 8, true, header_3.block_hash());
7270                 expect_payment_failed!(nodes[0], non_dust_hash, true);
7271         } else {
7272                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7273                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![bs_commitment_tx[0].clone()]}, 1);
7274                 check_closed_broadcast!(nodes[0], false);
7275                 check_added_monitors!(nodes[0], 1);
7276                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7277                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7278                 let parent_hash  = connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 2, true, header.block_hash());
7279                 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7280                 if !revoked {
7281                         expect_payment_failed!(nodes[0], dust_hash, true);
7282                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7283                         // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7284                         nodes[0].block_notifier.block_connected(&Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
7285                         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7286                         let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7287                         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 8, true, header_3.block_hash());
7288                         expect_payment_failed!(nodes[0], non_dust_hash, true);
7289                 } else {
7290                         // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7291                         // commitment tx
7292                         let events = nodes[0].node.get_and_clear_pending_events();
7293                         assert_eq!(events.len(), 2);
7294                         let first;
7295                         match events[0] {
7296                                 Event::PaymentFailed { payment_hash, .. } => {
7297                                         if payment_hash == dust_hash { first = true; }
7298                                         else { first = false; }
7299                                 },
7300                                 _ => panic!("Unexpected event"),
7301                         }
7302                         match events[1] {
7303                                 Event::PaymentFailed { payment_hash, .. } => {
7304                                         if first { assert_eq!(payment_hash, non_dust_hash); }
7305                                         else { assert_eq!(payment_hash, dust_hash); }
7306                                 },
7307                                 _ => panic!("Unexpected event"),
7308                         }
7309                 }
7310         }
7311 }
7312
7313 #[test]
7314 fn test_sweep_outbound_htlc_failure_update() {
7315         do_test_sweep_outbound_htlc_failure_update(false, true);
7316         do_test_sweep_outbound_htlc_failure_update(false, false);
7317         do_test_sweep_outbound_htlc_failure_update(true, false);
7318 }
7319
7320 #[test]
7321 fn test_upfront_shutdown_script() {
7322         // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
7323         // enforce it at shutdown message
7324
7325         let mut config = UserConfig::default();
7326         config.channel_options.announced_channel = true;
7327         config.peer_channel_config_limits.force_announced_channel_preference = false;
7328         config.channel_options.commit_upfront_shutdown_pubkey = false;
7329         let user_cfgs = [None, Some(config), None];
7330         let chanmon_cfgs = create_chanmon_cfgs(3);
7331         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7332         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7333         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7334
7335         // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
7336         let flags = InitFeatures::known();
7337         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7338         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7339         let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7340         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7341         // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that  we disconnect peer
7342         nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
7343     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()));
7344         check_added_monitors!(nodes[2], 1);
7345
7346         // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
7347         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7348         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7349         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7350         // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
7351         nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
7352         let events = nodes[2].node.get_and_clear_pending_msg_events();
7353         assert_eq!(events.len(), 1);
7354         match events[0] {
7355                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7356                 _ => panic!("Unexpected event"),
7357         }
7358
7359         // We test that if case of peer non-signaling we don't enforce committed script at channel opening
7360         let flags_no = InitFeatures::known().clear_upfront_shutdown_script();
7361         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone());
7362         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7363         let mut node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
7364         node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7365         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_1_shutdown);
7366         let events = nodes[1].node.get_and_clear_pending_msg_events();
7367         assert_eq!(events.len(), 1);
7368         match events[0] {
7369                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7370                 _ => panic!("Unexpected event"),
7371         }
7372
7373         // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7374         // channel smoothly, opt-out is from channel initiator here
7375         let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone());
7376         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7377         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7378         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7379         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
7380         let events = nodes[0].node.get_and_clear_pending_msg_events();
7381         assert_eq!(events.len(), 1);
7382         match events[0] {
7383                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7384                 _ => panic!("Unexpected event"),
7385         }
7386
7387         //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7388         //// channel smoothly
7389         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone());
7390         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7391         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7392         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7393         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
7394         let events = nodes[0].node.get_and_clear_pending_msg_events();
7395         assert_eq!(events.len(), 2);
7396         match events[0] {
7397                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7398                 _ => panic!("Unexpected event"),
7399         }
7400         match events[1] {
7401                 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7402                 _ => panic!("Unexpected event"),
7403         }
7404 }
7405
7406 #[test]
7407 fn test_user_configurable_csv_delay() {
7408         // We test our channel constructors yield errors when we pass them absurd csv delay
7409
7410         let mut low_our_to_self_config = UserConfig::default();
7411         low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7412         let mut high_their_to_self_config = UserConfig::default();
7413         high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7414         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7415         let chanmon_cfgs = create_chanmon_cfgs(2);
7416         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7417         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7418         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7419
7420         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7421         let keys_manager: Arc<KeysInterface<ChanKeySigner = EnforcingChannelKeys>> = Arc::new(test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet));
7422         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) {
7423                 match error {
7424                         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())); },
7425                         _ => panic!("Unexpected event"),
7426                 }
7427         } else { assert!(false) }
7428
7429         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7430         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7431         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7432         open_channel.to_self_delay = 200;
7433         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) {
7434                 match error {
7435                         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()));  },
7436                         _ => panic!("Unexpected event"),
7437                 }
7438         } else { assert!(false); }
7439
7440         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7441         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7442         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()));
7443         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7444         accept_channel.to_self_delay = 200;
7445         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7446         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7447                 match action {
7448                         &ErrorAction::SendErrorMessage { ref msg } => {
7449                                 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()));
7450                         },
7451                         _ => { assert!(false); }
7452                 }
7453         } else { assert!(false); }
7454
7455         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7456         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7457         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7458         open_channel.to_self_delay = 200;
7459         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) {
7460                 match error {
7461                         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())); },
7462                         _ => panic!("Unexpected event"),
7463                 }
7464         } else { assert!(false); }
7465 }
7466
7467 #[test]
7468 fn test_data_loss_protect() {
7469         // We want to be sure that :
7470         // * we don't broadcast our Local Commitment Tx in case of fallen behind
7471         // * we close channel in case of detecting other being fallen behind
7472         // * we are able to claim our own outputs thanks to to_remote being static
7473         let keys_manager;
7474         let logger;
7475         let fee_estimator;
7476         let tx_broadcaster;
7477         let chain_monitor;
7478         let monitor;
7479         let node_state_0;
7480         let chanmon_cfgs = create_chanmon_cfgs(2);
7481         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7482         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7483         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7484
7485         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7486
7487         // Cache node A state before any channel update
7488         let previous_node_state = nodes[0].node.encode();
7489         let mut previous_chan_monitor_state = test_utils::TestVecWriter(Vec::new());
7490         nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut previous_chan_monitor_state).unwrap();
7491
7492         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7493         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7494
7495         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7496         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7497
7498         // Restore node A from previous state
7499         logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7500         let mut chan_monitor = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut ::std::io::Cursor::new(previous_chan_monitor_state.0)).unwrap().1;
7501         chain_monitor = ChainWatchInterfaceUtil::new(Network::Testnet);
7502         tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
7503         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
7504         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
7505         monitor = test_utils::TestChannelMonitor::new(&chain_monitor, &tx_broadcaster, &logger, &fee_estimator);
7506         node_state_0 = {
7507                 let mut channel_monitors = HashMap::new();
7508                 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chan_monitor);
7509                 <(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 {
7510                         keys_manager: &keys_manager,
7511                         fee_estimator: &fee_estimator,
7512                         monitor: &monitor,
7513                         logger: &logger,
7514                         tx_broadcaster: &tx_broadcaster,
7515                         default_config: UserConfig::default(),
7516                         channel_monitors,
7517                 }).unwrap().1
7518         };
7519         nodes[0].node = &node_state_0;
7520         assert!(monitor.add_monitor(OutPoint { txid: chan.3.txid(), index: 0 }, chan_monitor).is_ok());
7521         nodes[0].chan_monitor = &monitor;
7522         nodes[0].chain_monitor = &chain_monitor;
7523
7524         nodes[0].block_notifier = BlockNotifier::new();
7525         nodes[0].block_notifier.register_listener(&nodes[0].chan_monitor.simple_monitor);
7526         nodes[0].block_notifier.register_listener(nodes[0].node);
7527
7528         check_added_monitors!(nodes[0], 1);
7529
7530         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7531         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7532
7533         let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7534
7535         // Check we don't broadcast any transactions following learning of per_commitment_point from B
7536         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7537         check_added_monitors!(nodes[0], 1);
7538
7539         {
7540                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7541                 assert_eq!(node_txn.len(), 0);
7542         }
7543
7544         let mut reestablish_1 = Vec::with_capacity(1);
7545         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7546                 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7547                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7548                         reestablish_1.push(msg.clone());
7549                 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7550                 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7551                         match action {
7552                                 &ErrorAction::SendErrorMessage { ref msg } => {
7553                                         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");
7554                                 },
7555                                 _ => panic!("Unexpected event!"),
7556                         }
7557                 } else {
7558                         panic!("Unexpected event")
7559                 }
7560         }
7561
7562         // Check we close channel detecting A is fallen-behind
7563         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7564         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7565         check_added_monitors!(nodes[1], 1);
7566
7567
7568         // Check A is able to claim to_remote output
7569         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7570         assert_eq!(node_txn.len(), 1);
7571         check_spends!(node_txn[0], chan.3);
7572         assert_eq!(node_txn[0].output.len(), 2);
7573         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
7574         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()]}, 0);
7575         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
7576         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
7577         assert_eq!(spend_txn.len(), 1);
7578         check_spends!(spend_txn[0], node_txn[0]);
7579 }
7580
7581 #[test]
7582 fn test_check_htlc_underpaying() {
7583         // Send payment through A -> B but A is maliciously
7584         // sending a probe payment (i.e less than expected value0
7585         // to B, B should refuse payment.
7586
7587         let chanmon_cfgs = create_chanmon_cfgs(2);
7588         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7589         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7590         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7591
7592         // Create some initial channels
7593         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7594
7595         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 10_000);
7596
7597         // Node 3 is expecting payment of 100_000 but receive 10_000,
7598         // fail htlc like we didn't know the preimage.
7599         nodes[1].node.claim_funds(payment_preimage, &None, 100_000);
7600         nodes[1].node.process_pending_htlc_forwards();
7601
7602         let events = nodes[1].node.get_and_clear_pending_msg_events();
7603         assert_eq!(events.len(), 1);
7604         let (update_fail_htlc, commitment_signed) = match events[0] {
7605                 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 } } => {
7606                         assert!(update_add_htlcs.is_empty());
7607                         assert!(update_fulfill_htlcs.is_empty());
7608                         assert_eq!(update_fail_htlcs.len(), 1);
7609                         assert!(update_fail_malformed_htlcs.is_empty());
7610                         assert!(update_fee.is_none());
7611                         (update_fail_htlcs[0].clone(), commitment_signed)
7612                 },
7613                 _ => panic!("Unexpected event"),
7614         };
7615         check_added_monitors!(nodes[1], 1);
7616
7617         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7618         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7619
7620         // 10_000 msat as u64, followed by a height of 99 as u32
7621         let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7622         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(99));
7623         expect_payment_failed!(nodes[0], payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7624         nodes[1].node.get_and_clear_pending_events();
7625 }
7626
7627 #[test]
7628 fn test_announce_disable_channels() {
7629         // Create 2 channels between A and B. Disconnect B. Call timer_chan_freshness_every_min and check for generated
7630         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7631
7632         let chanmon_cfgs = create_chanmon_cfgs(2);
7633         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7634         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7635         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7636
7637         let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7638         let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7639         let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7640
7641         // Disconnect peers
7642         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7643         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7644
7645         nodes[0].node.timer_chan_freshness_every_min(); // dirty -> stagged
7646         nodes[0].node.timer_chan_freshness_every_min(); // staged -> fresh
7647         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7648         assert_eq!(msg_events.len(), 3);
7649         for e in msg_events {
7650                 match e {
7651                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7652                                 let short_id = msg.contents.short_channel_id;
7653                                 // Check generated channel_update match list in PendingChannelUpdate
7654                                 if short_id != short_id_1 && short_id != short_id_2 && short_id != short_id_3 {
7655                                         panic!("Generated ChannelUpdate for wrong chan!");
7656                                 }
7657                         },
7658                         _ => panic!("Unexpected event"),
7659                 }
7660         }
7661         // Reconnect peers
7662         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7663         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7664         assert_eq!(reestablish_1.len(), 3);
7665         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7666         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7667         assert_eq!(reestablish_2.len(), 3);
7668
7669         // Reestablish chan_1
7670         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7671         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7672         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7673         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7674         // Reestablish chan_2
7675         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7676         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7677         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7678         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7679         // Reestablish chan_3
7680         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7681         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7682         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7683         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7684
7685         nodes[0].node.timer_chan_freshness_every_min();
7686         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7687 }
7688
7689 #[test]
7690 fn test_bump_penalty_txn_on_revoked_commitment() {
7691         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7692         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7693
7694         let chanmon_cfgs = create_chanmon_cfgs(2);
7695         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7696         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7697         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7698
7699         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7700         let logger = test_utils::TestLogger::new();
7701
7702
7703         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7704         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
7705         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();
7706         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7707
7708         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7709         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7710         assert_eq!(revoked_txn[0].output.len(), 4);
7711         assert_eq!(revoked_txn[0].input.len(), 1);
7712         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7713         let revoked_txid = revoked_txn[0].txid();
7714
7715         let mut penalty_sum = 0;
7716         for outp in revoked_txn[0].output.iter() {
7717                 if outp.script_pubkey.is_v0_p2wsh() {
7718                         penalty_sum += outp.value;
7719                 }
7720         }
7721
7722         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7723         let header_114 = connect_blocks(&nodes[1].block_notifier, 114, 0, false, Default::default());
7724
7725         // Actually revoke tx by claiming a HTLC
7726         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7727         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7728         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_txn[0].clone()] }, 115);
7729         check_added_monitors!(nodes[1], 1);
7730
7731         // One or more justice tx should have been broadcast, check it
7732         let penalty_1;
7733         let feerate_1;
7734         {
7735                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7736                 assert_eq!(node_txn.len(), 3); // justice tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout (broadcasted from ChannelManager)
7737                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7738                 assert_eq!(node_txn[0].output.len(), 1);
7739                 check_spends!(node_txn[0], revoked_txn[0]);
7740                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7741                 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7742                 penalty_1 = node_txn[0].txid();
7743                 node_txn.clear();
7744         };
7745
7746         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7747         let header = connect_blocks(&nodes[1].block_notifier, 3, 115,  true, header.block_hash());
7748         let mut penalty_2 = penalty_1;
7749         let mut feerate_2 = 0;
7750         {
7751                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7752                 assert_eq!(node_txn.len(), 1);
7753                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7754                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7755                         assert_eq!(node_txn[0].output.len(), 1);
7756                         check_spends!(node_txn[0], revoked_txn[0]);
7757                         penalty_2 = node_txn[0].txid();
7758                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7759                         assert_ne!(penalty_2, penalty_1);
7760                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7761                         feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7762                         // Verify 25% bump heuristic
7763                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7764                         node_txn.clear();
7765                 }
7766         }
7767         assert_ne!(feerate_2, 0);
7768
7769         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7770         connect_blocks(&nodes[1].block_notifier, 3, 118, true, header);
7771         let penalty_3;
7772         let mut feerate_3 = 0;
7773         {
7774                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7775                 assert_eq!(node_txn.len(), 1);
7776                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7777                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7778                         assert_eq!(node_txn[0].output.len(), 1);
7779                         check_spends!(node_txn[0], revoked_txn[0]);
7780                         penalty_3 = node_txn[0].txid();
7781                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7782                         assert_ne!(penalty_3, penalty_2);
7783                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7784                         feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7785                         // Verify 25% bump heuristic
7786                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7787                         node_txn.clear();
7788                 }
7789         }
7790         assert_ne!(feerate_3, 0);
7791
7792         nodes[1].node.get_and_clear_pending_events();
7793         nodes[1].node.get_and_clear_pending_msg_events();
7794 }
7795
7796 #[test]
7797 fn test_bump_penalty_txn_on_revoked_htlcs() {
7798         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7799         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7800
7801         let chanmon_cfgs = create_chanmon_cfgs(2);
7802         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7803         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7804         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7805
7806         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7807         // Lock HTLC in both directions
7808         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3_000_000).0;
7809         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7810
7811         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7812         assert_eq!(revoked_local_txn[0].input.len(), 1);
7813         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7814
7815         // Revoke local commitment tx
7816         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7817
7818         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7819         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7820         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
7821         check_closed_broadcast!(nodes[1], false);
7822         check_added_monitors!(nodes[1], 1);
7823
7824         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7825         assert_eq!(revoked_htlc_txn.len(), 4);
7826         if revoked_htlc_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7827                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7828                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7829                 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7830                 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7831                 assert_eq!(revoked_htlc_txn[1].output.len(), 1);
7832                 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7833         } else if revoked_htlc_txn[1].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7834                 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7835                 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7836                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7837                 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7838                 assert_eq!(revoked_htlc_txn[0].output.len(), 1);
7839                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7840         }
7841
7842         // Broadcast set of revoked txn on A
7843         let header_128 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7844         nodes[0].block_notifier.block_connected(&Block { header: header_128, txdata: vec![revoked_local_txn[0].clone()] }, 128);
7845         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7846         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7847         nodes[0].block_notifier.block_connected(&Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()] }, 129);
7848         let first;
7849         let feerate_1;
7850         let penalty_txn;
7851         {
7852                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7853                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7854                 // Verify claim tx are spending revoked HTLC txn
7855
7856                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7857                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7858                 // which are included in the same block (they are broadcasted because we scan the
7859                 // transactions linearly and generate claims as we go, they likely should be removed in the
7860                 // future).
7861                 assert_eq!(node_txn[0].input.len(), 1);
7862                 check_spends!(node_txn[0], revoked_local_txn[0]);
7863                 assert_eq!(node_txn[1].input.len(), 1);
7864                 check_spends!(node_txn[1], revoked_local_txn[0]);
7865                 assert_eq!(node_txn[2].input.len(), 1);
7866                 check_spends!(node_txn[2], revoked_local_txn[0]);
7867
7868                 // Each of the three justice transactions claim a separate (single) output of the three
7869                 // available, which we check here:
7870                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7871                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7872                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7873
7874                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7875                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7876
7877                 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7878                 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7879                 // a remote commitment tx has already been confirmed).
7880                 check_spends!(node_txn[3], chan.3);
7881
7882                 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7883                 // output, checked above).
7884                 assert_eq!(node_txn[4].input.len(), 2);
7885                 assert_eq!(node_txn[4].output.len(), 1);
7886                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7887
7888                 first = node_txn[4].txid();
7889                 // Store both feerates for later comparison
7890                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[4].output[0].value;
7891                 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7892                 penalty_txn = vec![node_txn[2].clone()];
7893                 node_txn.clear();
7894         }
7895
7896         // Connect one more block to see if bumped penalty are issued for HTLC txn
7897         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7898         nodes[0].block_notifier.block_connected(&Block { header: header_130, txdata: penalty_txn }, 130);
7899         let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7900         nodes[0].block_notifier.block_connected(&Block { header: header_131, txdata: Vec::new() }, 131);
7901         {
7902                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7903                 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7904
7905                 check_spends!(node_txn[0], revoked_local_txn[0]);
7906                 check_spends!(node_txn[1], revoked_local_txn[0]);
7907                 // Note that these are both bogus - they spend outputs already claimed in block 129:
7908                 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output  {
7909                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7910                 } else {
7911                         assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7912                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7913                 }
7914
7915                 node_txn.clear();
7916         };
7917
7918         // Few more blocks to confirm penalty txn
7919         let header_135 = connect_blocks(&nodes[0].block_notifier, 4, 131, true, header_131.block_hash());
7920         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7921         let header_144 = connect_blocks(&nodes[0].block_notifier, 9, 135, true, header_135);
7922         let node_txn = {
7923                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7924                 assert_eq!(node_txn.len(), 1);
7925
7926                 assert_eq!(node_txn[0].input.len(), 2);
7927                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7928                 // Verify bumped tx is different and 25% bump heuristic
7929                 assert_ne!(first, node_txn[0].txid());
7930                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7931                 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7932                 assert!(feerate_2 * 100 > feerate_1 * 125);
7933                 let txn = vec![node_txn[0].clone()];
7934                 node_txn.clear();
7935                 txn
7936         };
7937         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7938         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7939         nodes[0].block_notifier.block_connected(&Block { header: header_145, txdata: node_txn }, 145);
7940         connect_blocks(&nodes[0].block_notifier, 20, 145, true, header_145.block_hash());
7941         {
7942                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7943                 // We verify than no new transaction has been broadcast because previously
7944                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7945                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7946                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7947                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7948                 // up bumped justice generation.
7949                 assert_eq!(node_txn.len(), 0);
7950                 node_txn.clear();
7951         }
7952         check_closed_broadcast!(nodes[0], false);
7953         check_added_monitors!(nodes[0], 1);
7954 }
7955
7956 #[test]
7957 fn test_bump_penalty_txn_on_remote_commitment() {
7958         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7959         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7960
7961         // Create 2 HTLCs
7962         // Provide preimage for one
7963         // Check aggregation
7964
7965         let chanmon_cfgs = create_chanmon_cfgs(2);
7966         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7967         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7968         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7969
7970         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7971         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7972         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7973
7974         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7975         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7976         assert_eq!(remote_txn[0].output.len(), 4);
7977         assert_eq!(remote_txn[0].input.len(), 1);
7978         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7979
7980         // Claim a HTLC without revocation (provide B monitor with preimage)
7981         nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000);
7982         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7983         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
7984         check_added_monitors!(nodes[1], 2);
7985
7986         // One or more claim tx should have been broadcast, check it
7987         let timeout;
7988         let preimage;
7989         let feerate_timeout;
7990         let feerate_preimage;
7991         {
7992                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7993                 assert_eq!(node_txn.len(), 5); // 2 * claim tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout + local HTLC-success (broadcasted from ChannelManager)
7994                 assert_eq!(node_txn[0].input.len(), 1);
7995                 assert_eq!(node_txn[1].input.len(), 1);
7996                 check_spends!(node_txn[0], remote_txn[0]);
7997                 check_spends!(node_txn[1], remote_txn[0]);
7998                 check_spends!(node_txn[2], chan.3);
7999                 check_spends!(node_txn[3], node_txn[2]);
8000                 check_spends!(node_txn[4], node_txn[2]);
8001                 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
8002                         timeout = node_txn[0].txid();
8003                         let index = node_txn[0].input[0].previous_output.vout;
8004                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8005                         feerate_timeout = fee * 1000 / node_txn[0].get_weight() as u64;
8006
8007                         preimage = node_txn[1].txid();
8008                         let index = node_txn[1].input[0].previous_output.vout;
8009                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
8010                         feerate_preimage = fee * 1000 / node_txn[1].get_weight() as u64;
8011                 } else {
8012                         timeout = node_txn[1].txid();
8013                         let index = node_txn[1].input[0].previous_output.vout;
8014                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
8015                         feerate_timeout = fee * 1000 / node_txn[1].get_weight() as u64;
8016
8017                         preimage = node_txn[0].txid();
8018                         let index = node_txn[0].input[0].previous_output.vout;
8019                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8020                         feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
8021                 }
8022                 node_txn.clear();
8023         };
8024         assert_ne!(feerate_timeout, 0);
8025         assert_ne!(feerate_preimage, 0);
8026
8027         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
8028         connect_blocks(&nodes[1].block_notifier, 15, 1,  true, header.block_hash());
8029         {
8030                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8031                 assert_eq!(node_txn.len(), 2);
8032                 assert_eq!(node_txn[0].input.len(), 1);
8033                 assert_eq!(node_txn[1].input.len(), 1);
8034                 check_spends!(node_txn[0], remote_txn[0]);
8035                 check_spends!(node_txn[1], remote_txn[0]);
8036                 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
8037                         let index = node_txn[0].input[0].previous_output.vout;
8038                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8039                         let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
8040                         assert!(new_feerate * 100 > feerate_timeout * 125);
8041                         assert_ne!(timeout, node_txn[0].txid());
8042
8043                         let index = node_txn[1].input[0].previous_output.vout;
8044                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
8045                         let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
8046                         assert!(new_feerate * 100 > feerate_preimage * 125);
8047                         assert_ne!(preimage, node_txn[1].txid());
8048                 } else {
8049                         let index = node_txn[1].input[0].previous_output.vout;
8050                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
8051                         let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
8052                         assert!(new_feerate * 100 > feerate_timeout * 125);
8053                         assert_ne!(timeout, node_txn[1].txid());
8054
8055                         let index = node_txn[0].input[0].previous_output.vout;
8056                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8057                         let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
8058                         assert!(new_feerate * 100 > feerate_preimage * 125);
8059                         assert_ne!(preimage, node_txn[0].txid());
8060                 }
8061                 node_txn.clear();
8062         }
8063
8064         nodes[1].node.get_and_clear_pending_events();
8065         nodes[1].node.get_and_clear_pending_msg_events();
8066 }
8067
8068 #[test]
8069 fn test_set_outpoints_partial_claiming() {
8070         // - remote party claim tx, new bump tx
8071         // - disconnect remote claiming tx, new bump
8072         // - disconnect tx, see no tx anymore
8073         let chanmon_cfgs = create_chanmon_cfgs(2);
8074         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8075         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8076         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8077
8078         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8079         let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
8080         let payment_preimage_2 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
8081
8082         // Remote commitment txn with 4 outputs: to_local, to_remote, 2 outgoing HTLC
8083         let remote_txn = get_local_commitment_txn!(nodes[1], chan.2);
8084         assert_eq!(remote_txn.len(), 3);
8085         assert_eq!(remote_txn[0].output.len(), 4);
8086         assert_eq!(remote_txn[0].input.len(), 1);
8087         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
8088         check_spends!(remote_txn[1], remote_txn[0]);
8089         check_spends!(remote_txn[2], remote_txn[0]);
8090
8091         // Connect blocks on node A to advance height towards TEST_FINAL_CLTV
8092         let prev_header_100 = connect_blocks(&nodes[1].block_notifier, 100, 0, false, Default::default());
8093         // Provide node A with both preimage
8094         nodes[0].node.claim_funds(payment_preimage_1, &None, 3_000_000);
8095         nodes[0].node.claim_funds(payment_preimage_2, &None, 3_000_000);
8096         check_added_monitors!(nodes[0], 2);
8097         nodes[0].node.get_and_clear_pending_events();
8098         nodes[0].node.get_and_clear_pending_msg_events();
8099
8100         // Connect blocks on node A commitment transaction
8101         let header = BlockHeader { version: 0x20000000, prev_blockhash: prev_header_100, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8102         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 101);
8103         check_closed_broadcast!(nodes[0], false);
8104         check_added_monitors!(nodes[0], 1);
8105         // Verify node A broadcast tx claiming both HTLCs
8106         {
8107                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8108                 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-Success*2
8109                 assert_eq!(node_txn.len(), 4);
8110                 check_spends!(node_txn[0], remote_txn[0]);
8111                 check_spends!(node_txn[1], chan.3);
8112                 check_spends!(node_txn[2], node_txn[1]);
8113                 check_spends!(node_txn[3], node_txn[1]);
8114                 assert_eq!(node_txn[0].input.len(), 2);
8115                 node_txn.clear();
8116         }
8117
8118         // Connect blocks on node B
8119         connect_blocks(&nodes[1].block_notifier, 135, 0, false, Default::default());
8120         check_closed_broadcast!(nodes[1], false);
8121         check_added_monitors!(nodes[1], 1);
8122         // Verify node B broadcast 2 HTLC-timeout txn
8123         let partial_claim_tx = {
8124                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8125                 assert_eq!(node_txn.len(), 3);
8126                 check_spends!(node_txn[1], node_txn[0]);
8127                 check_spends!(node_txn[2], node_txn[0]);
8128                 assert_eq!(node_txn[1].input.len(), 1);
8129                 assert_eq!(node_txn[2].input.len(), 1);
8130                 node_txn[1].clone()
8131         };
8132
8133         // Broadcast partial claim on node A, should regenerate a claiming tx with HTLC dropped
8134         let header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8135         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![partial_claim_tx.clone()] }, 102);
8136         {
8137                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8138                 assert_eq!(node_txn.len(), 1);
8139                 check_spends!(node_txn[0], remote_txn[0]);
8140                 assert_eq!(node_txn[0].input.len(), 1); //dropped HTLC
8141                 node_txn.clear();
8142         }
8143         nodes[0].node.get_and_clear_pending_msg_events();
8144
8145         // Disconnect last block on node A, should regenerate a claiming tx with HTLC dropped
8146         nodes[0].block_notifier.block_disconnected(&header, 102);
8147         {
8148                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8149                 assert_eq!(node_txn.len(), 1);
8150                 check_spends!(node_txn[0], remote_txn[0]);
8151                 assert_eq!(node_txn[0].input.len(), 2); //resurrected HTLC
8152                 node_txn.clear();
8153         }
8154
8155         //// Disconnect one more block and then reconnect multiple no transaction should be generated
8156         nodes[0].block_notifier.block_disconnected(&header, 101);
8157         connect_blocks(&nodes[1].block_notifier, 15, 101, false, prev_header_100);
8158         {
8159                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8160                 assert_eq!(node_txn.len(), 0);
8161                 node_txn.clear();
8162         }
8163 }
8164
8165 #[test]
8166 fn test_counterparty_raa_skip_no_crash() {
8167         // Previously, if our counterparty sent two RAAs in a row without us having provided a
8168         // commitment transaction, we would have happily carried on and provided them the next
8169         // commitment transaction based on one RAA forward. This would probably eventually have led to
8170         // channel closure, but it would not have resulted in funds loss. Still, our
8171         // EnforcingChannelKeys would have paniced as it doesn't like jumps into the future. Here, we
8172         // check simply that the channel is closed in response to such an RAA, but don't check whether
8173         // we decide to punish our counterparty for revoking their funds (as we don't currently
8174         // implement that).
8175         let chanmon_cfgs = create_chanmon_cfgs(2);
8176         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8177         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8178         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8179         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8180
8181         let mut guard = nodes[0].node.channel_state.lock().unwrap();
8182         let keys = &guard.by_id.get_mut(&channel_id).unwrap().holder_keys;
8183         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8184         let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8185                 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8186         let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8187
8188         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8189                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8190         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8191         check_added_monitors!(nodes[1], 1);
8192 }
8193
8194 #[test]
8195 fn test_bump_txn_sanitize_tracking_maps() {
8196         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8197         // verify we clean then right after expiration of ANTI_REORG_DELAY.
8198
8199         let chanmon_cfgs = create_chanmon_cfgs(2);
8200         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8201         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8202         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8203
8204         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8205         // Lock HTLC in both directions
8206         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8207         route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8208
8209         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8210         assert_eq!(revoked_local_txn[0].input.len(), 1);
8211         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8212
8213         // Revoke local commitment tx
8214         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 9_000_000);
8215
8216         // Broadcast set of revoked txn on A
8217         let header_128 = connect_blocks(&nodes[0].block_notifier, 128, 0,  false, Default::default());
8218         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8219
8220         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8221         nodes[0].block_notifier.block_connected(&Block { header: header_129, txdata: vec![revoked_local_txn[0].clone()] }, 129);
8222         check_closed_broadcast!(nodes[0], false);
8223         check_added_monitors!(nodes[0], 1);
8224         let penalty_txn = {
8225                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8226                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8227                 check_spends!(node_txn[0], revoked_local_txn[0]);
8228                 check_spends!(node_txn[1], revoked_local_txn[0]);
8229                 check_spends!(node_txn[2], revoked_local_txn[0]);
8230                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8231                 node_txn.clear();
8232                 penalty_txn
8233         };
8234         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8235         nodes[0].block_notifier.block_connected(&Block { header: header_130, txdata: penalty_txn }, 130);
8236         connect_blocks(&nodes[0].block_notifier, 5, 130,  false, header_130.block_hash());
8237         {
8238                 let monitors = nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap();
8239                 if let Some(monitor) = monitors.get(&OutPoint { txid: chan.3.txid(), index: 0 }) {
8240                         assert!(monitor.onchain_tx_handler.pending_claim_requests.is_empty());
8241                         assert!(monitor.onchain_tx_handler.claimable_outpoints.is_empty());
8242                 }
8243         }
8244 }
8245
8246 #[test]
8247 fn test_override_channel_config() {
8248         let chanmon_cfgs = create_chanmon_cfgs(2);
8249         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8250         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8251         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8252
8253         // Node0 initiates a channel to node1 using the override config.
8254         let mut override_config = UserConfig::default();
8255         override_config.own_channel_config.our_to_self_delay = 200;
8256
8257         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8258
8259         // Assert the channel created by node0 is using the override config.
8260         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8261         assert_eq!(res.channel_flags, 0);
8262         assert_eq!(res.to_self_delay, 200);
8263 }
8264
8265 #[test]
8266 fn test_override_0msat_htlc_minimum() {
8267         let mut zero_config = UserConfig::default();
8268         zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8269         let chanmon_cfgs = create_chanmon_cfgs(2);
8270         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8271         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8272         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8273
8274         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8275         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8276         assert_eq!(res.htlc_minimum_msat, 1);
8277
8278         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8279         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8280         assert_eq!(res.htlc_minimum_msat, 1);
8281 }
8282
8283 #[test]
8284 fn test_simple_payment_secret() {
8285         // Simple test of sending a payment with a payment_secret present. This does not use any AMP
8286         // features, however.
8287         let chanmon_cfgs = create_chanmon_cfgs(3);
8288         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8289         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8290         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8291
8292         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8293         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
8294         let logger = test_utils::TestLogger::new();
8295
8296         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8297         let payment_secret = PaymentSecret([0xdb; 32]);
8298         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8299         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();
8300         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2]]], 100000, payment_hash, Some(payment_secret.clone()));
8301         // Claiming with all the correct values but the wrong secret should result in nothing...
8302         assert_eq!(nodes[2].node.claim_funds(payment_preimage, &None, 100_000), false);
8303         assert_eq!(nodes[2].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 100_000), false);
8304         // ...but with the right secret we should be able to claim all the way back
8305         claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage, Some(payment_secret.clone()), 100_000);
8306 }
8307
8308 #[test]
8309 fn test_simple_mpp() {
8310         // Simple test of sending a multi-path payment.
8311         let chanmon_cfgs = create_chanmon_cfgs(4);
8312         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8313         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8314         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8315
8316         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8317         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8318         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8319         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8320         let logger = test_utils::TestLogger::new();
8321
8322         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8323         let payment_secret = PaymentSecret([0xdb; 32]);
8324         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8325         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();
8326         let path = route.paths[0].clone();
8327         route.paths.push(path);
8328         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8329         route.paths[0][0].short_channel_id = chan_1_id;
8330         route.paths[0][1].short_channel_id = chan_3_id;
8331         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8332         route.paths[1][0].short_channel_id = chan_2_id;
8333         route.paths[1][1].short_channel_id = chan_4_id;
8334         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, Some(payment_secret.clone()));
8335         // Claiming with all the correct values but the wrong secret should result in nothing...
8336         assert_eq!(nodes[3].node.claim_funds(payment_preimage, &None, 200_000), false);
8337         assert_eq!(nodes[3].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 200_000), false);
8338         // ...but with the right secret we should be able to claim all the way back
8339         claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage, Some(payment_secret), 200_000);
8340 }
8341
8342 #[test]
8343 fn test_update_err_monitor_lockdown() {
8344         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8345         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8346         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8347         //
8348         // This scenario may happen in a watchtower setup, where watchtower process a block height
8349         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8350         // commitment at same time.
8351
8352         let chanmon_cfgs = create_chanmon_cfgs(2);
8353         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8354         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8355         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8356
8357         // Create some initial channel
8358         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8359         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8360
8361         // Rebalance the network to generate htlc in the two directions
8362         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8363
8364         // Route a HTLC from node 0 to node 1 (but don't settle)
8365         let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8366
8367         // Copy SimpleManyChannelMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8368         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8369         let chain_monitor = chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet);
8370         let watchtower = {
8371                 let monitors = nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap();
8372                 let monitor = monitors.get(&outpoint).unwrap();
8373                 let mut w = test_utils::TestVecWriter(Vec::new());
8374                 monitor.write_for_disk(&mut w).unwrap();
8375                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
8376                                 &mut ::std::io::Cursor::new(&w.0)).unwrap().1;
8377                 assert!(new_monitor == *monitor);
8378                 let watchtower = test_utils::TestChannelMonitor::new(&chain_monitor, &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator);
8379                 assert!(watchtower.add_monitor(outpoint, new_monitor).is_ok());
8380                 watchtower
8381         };
8382         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8383         watchtower.simple_monitor.block_connected(&header, &[], 200);
8384
8385         // Try to update ChannelMonitor
8386         assert!(nodes[1].node.claim_funds(preimage, &None, 9_000_000));
8387         check_added_monitors!(nodes[1], 1);
8388         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8389         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8390         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8391         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8392                 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8393                         if let Err(_) =  watchtower.simple_monitor.update_monitor(outpoint, update.clone()) {} else { assert!(false); }
8394                         if let Ok(_) = nodes[0].chan_monitor.update_monitor(outpoint, update) {} else { assert!(false); }
8395                 } else { assert!(false); }
8396         } else { assert!(false); };
8397         // Our local monitor is in-sync and hasn't processed yet timeout
8398         check_added_monitors!(nodes[0], 1);
8399         let events = nodes[0].node.get_and_clear_pending_events();
8400         assert_eq!(events.len(), 1);
8401 }
8402
8403 #[test]
8404 fn test_concurrent_monitor_claim() {
8405         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8406         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8407         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8408         // state N+1 confirms. Alice claims output from state N+1.
8409
8410         let chanmon_cfgs = create_chanmon_cfgs(2);
8411         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8412         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8413         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8414
8415         // Create some initial channel
8416         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8417         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8418
8419         // Rebalance the network to generate htlc in the two directions
8420         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8421
8422         // Route a HTLC from node 0 to node 1 (but don't settle)
8423         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8424
8425         // Copy SimpleManyChannelMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8426         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8427         let chain_monitor = chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet);
8428         let watchtower_alice = {
8429                 let monitors = nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap();
8430                 let monitor = monitors.get(&outpoint).unwrap();
8431                 let mut w = test_utils::TestVecWriter(Vec::new());
8432                 monitor.write_for_disk(&mut w).unwrap();
8433                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
8434                                 &mut ::std::io::Cursor::new(&w.0)).unwrap().1;
8435                 assert!(new_monitor == *monitor);
8436                 let watchtower = test_utils::TestChannelMonitor::new(&chain_monitor, &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator);
8437                 assert!(watchtower.add_monitor(outpoint, new_monitor).is_ok());
8438                 watchtower
8439         };
8440         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8441         watchtower_alice.simple_monitor.block_connected(&header, &vec![], 135);
8442
8443         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8444         {
8445                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8446                 assert_eq!(txn.len(), 2);
8447                 txn.clear();
8448         }
8449
8450         // Copy SimpleManyChannelMonitor to simulate watchtower Bob and make it receive a commitment update first.
8451         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8452         let chain_monitor = chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet);
8453         let watchtower_bob = {
8454                 let monitors = nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap();
8455                 let monitor = monitors.get(&outpoint).unwrap();
8456                 let mut w = test_utils::TestVecWriter(Vec::new());
8457                 monitor.write_for_disk(&mut w).unwrap();
8458                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
8459                                 &mut ::std::io::Cursor::new(&w.0)).unwrap().1;
8460                 assert!(new_monitor == *monitor);
8461                 let watchtower = test_utils::TestChannelMonitor::new(&chain_monitor, &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator);
8462                 assert!(watchtower.add_monitor(outpoint, new_monitor).is_ok());
8463                 watchtower
8464         };
8465         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8466         watchtower_bob.simple_monitor.block_connected(&header, &vec![], 134);
8467
8468         // Route another payment to generate another update with still previous HTLC pending
8469         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
8470         {
8471                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
8472                 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();
8473                 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
8474         }
8475         check_added_monitors!(nodes[1], 1);
8476
8477         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8478         assert_eq!(updates.update_add_htlcs.len(), 1);
8479         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8480         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8481                 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8482                         // Watchtower Alice should already have seen the block and reject the update
8483                         if let Err(_) =  watchtower_alice.simple_monitor.update_monitor(outpoint, update.clone()) {} else { assert!(false); }
8484                         if let Ok(_) = watchtower_bob.simple_monitor.update_monitor(outpoint, update.clone()) {} else { assert!(false); }
8485                         if let Ok(_) = nodes[0].chan_monitor.update_monitor(outpoint, update) {} else { assert!(false); }
8486                 } else { assert!(false); }
8487         } else { assert!(false); };
8488         // Our local monitor is in-sync and hasn't processed yet timeout
8489         check_added_monitors!(nodes[0], 1);
8490
8491         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8492         watchtower_bob.simple_monitor.block_connected(&header, &vec![], 135);
8493
8494         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8495         let bob_state_y;
8496         {
8497                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8498                 assert_eq!(txn.len(), 2);
8499                 bob_state_y = txn[0].clone();
8500                 txn.clear();
8501         };
8502
8503         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8504         watchtower_alice.simple_monitor.block_connected(&header, &vec![(0, &bob_state_y)], 136);
8505         {
8506                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8507                 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8508                 // the onchain detection of the HTLC output
8509                 assert_eq!(htlc_txn.len(), 2);
8510                 check_spends!(htlc_txn[0], bob_state_y);
8511                 check_spends!(htlc_txn[1], bob_state_y);
8512         }
8513 }