66da8ed4e5941d6c123b419e88cf06bbb8acda1e
[rust-lightning] / lightning / src / ln / functional_tests.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
13
14 use chain::transaction::OutPoint;
15 use chain::keysinterface::{ChannelKeys, KeysInterface, SpendableOutputDescriptor};
16 use chain::chaininterface;
17 use chain::chaininterface::{ChainListener, ChainWatchInterfaceUtil, BlockNotifier};
18 use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
19 use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, RAACommitmentOrder, PaymentPreimage, PaymentHash, PaymentSecret, PaymentSendFailure, BREAKDOWN_TIMEOUT};
20 use ln::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ManyChannelMonitor, ANTI_REORG_DELAY};
21 use ln::channelmonitor;
22 use ln::channel::{Channel, ChannelError};
23 use ln::{chan_utils, onion_utils};
24 use routing::router::{Route, RouteHop, get_route};
25 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
26 use ln::msgs;
27 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler,HTLCFailChannelUpdate, ErrorAction};
28 use util::enforcing_trait_impls::EnforcingChannelKeys;
29 use util::{byte_utils, test_utils};
30 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
31 use util::errors::APIError;
32 use util::ser::{Writeable, ReadableArgs, Readable};
33 use util::config::UserConfig;
34
35 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
36 use bitcoin::hashes::HashEngine;
37 use bitcoin::hash_types::{Txid, BlockHash, WPubkeyHash};
38 use bitcoin::util::bip143;
39 use bitcoin::util::address::Address;
40 use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
41 use bitcoin::blockdata::block::{Block, BlockHeader};
42 use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType, OutPoint as BitcoinOutPoint};
43 use bitcoin::blockdata::script::{Builder, Script};
44 use bitcoin::blockdata::opcodes;
45 use bitcoin::blockdata::constants::genesis_block;
46 use bitcoin::network::constants::Network;
47
48 use bitcoin::hashes::sha256::Hash as Sha256;
49 use bitcoin::hashes::Hash;
50
51 use bitcoin::secp256k1::{Secp256k1, Message};
52 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
53
54 use regex;
55
56 use std::collections::{BTreeSet, HashMap, HashSet};
57 use std::default::Default;
58 use std::sync::{Arc, Mutex};
59 use std::sync::atomic::Ordering;
60 use std::mem;
61
62 use ln::functional_test_utils::*;
63 use ln::chan_utils::PreCalculatedTxCreationKeys;
64
65 #[test]
66 fn test_insane_channel_opens() {
67         // Stand up a network of 2 nodes
68         let chanmon_cfgs = create_chanmon_cfgs(2);
69         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
70         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
71         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
72
73         // Instantiate channel parameters where we push the maximum msats given our
74         // funding satoshis
75         let channel_value_sat = 31337; // same as funding satoshis
76         let channel_reserve_satoshis = Channel::<EnforcingChannelKeys>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
77         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
78
79         // Have node0 initiate a channel to node1 with aforementioned parameters
80         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
81
82         // Extract the channel open message from node0 to node1
83         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
84
85         // Test helper that asserts we get the correct error string given a mutator
86         // that supposedly makes the channel open message insane
87         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
88                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
89                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
90                 assert_eq!(msg_events.len(), 1);
91                 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
92                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
93                         match action {
94                                 &ErrorAction::SendErrorMessage { .. } => {
95                                         nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
96                                 },
97                                 _ => panic!("unexpected event!"),
98                         }
99                 } else { assert!(false); }
100         };
101
102         use ln::channel::MAX_FUNDING_SATOSHIS;
103         use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
104
105         // Test all mutations that would make the channel open message insane
106         insane_open_helper(format!("Funding must be smaller than {}. It was {}", MAX_FUNDING_SATOSHIS, MAX_FUNDING_SATOSHIS).as_str(), |mut msg| { msg.funding_satoshis = MAX_FUNDING_SATOSHIS; msg });
107
108         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
109
110         insane_open_helper(r"push_msat \d+ was larger than funding value \d+", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
111
112         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
113
114         insane_open_helper(r"Bogus; channel reserve \(\d+\) is less than dust limit \(\d+\)", |mut msg| { msg.dust_limit_satoshis = msg.channel_reserve_satoshis + 1; msg });
115
116         insane_open_helper(r"Minimum htlc value \(\d+\) was larger than full channel value \(\d+\)", |mut msg| { msg.htlc_minimum_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000; msg });
117
118         insane_open_helper("They wanted our payments to be delayed by a needlessly long period", |mut msg| { msg.to_self_delay = MAX_LOCAL_BREAKDOWN_TIMEOUT + 1; msg });
119
120         insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
121
122         insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
123 }
124
125 #[test]
126 fn test_async_inbound_update_fee() {
127         let chanmon_cfgs = create_chanmon_cfgs(2);
128         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
129         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
130         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
131         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
132         let logger = test_utils::TestLogger::new();
133         let channel_id = chan.2;
134
135         // balancing
136         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
137
138         // A                                        B
139         // update_fee                            ->
140         // send (1) commitment_signed            -.
141         //                                       <- update_add_htlc/commitment_signed
142         // send (2) RAA (awaiting remote revoke) -.
143         // (1) commitment_signed is delivered    ->
144         //                                       .- send (3) RAA (awaiting remote revoke)
145         // (2) RAA is delivered                  ->
146         //                                       .- send (4) commitment_signed
147         //                                       <- (3) RAA is delivered
148         // send (5) commitment_signed            -.
149         //                                       <- (4) commitment_signed is delivered
150         // send (6) RAA                          -.
151         // (5) commitment_signed is delivered    ->
152         //                                       <- RAA
153         // (6) RAA is delivered                  ->
154
155         // First nodes[0] generates an update_fee
156         nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
157         check_added_monitors!(nodes[0], 1);
158
159         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
160         assert_eq!(events_0.len(), 1);
161         let (update_msg, commitment_signed) = match events_0[0] { // (1)
162                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
163                         (update_fee.as_ref(), commitment_signed)
164                 },
165                 _ => panic!("Unexpected event"),
166         };
167
168         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
169
170         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
171         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
172         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
173         nodes[1].node.send_payment(&get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV, &logger).unwrap(), our_payment_hash, &None).unwrap();
174         check_added_monitors!(nodes[1], 1);
175
176         let payment_event = {
177                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
178                 assert_eq!(events_1.len(), 1);
179                 SendEvent::from_event(events_1.remove(0))
180         };
181         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
182         assert_eq!(payment_event.msgs.len(), 1);
183
184         // ...now when the messages get delivered everyone should be happy
185         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
186         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
187         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
188         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
189         check_added_monitors!(nodes[0], 1);
190
191         // deliver(1), generate (3):
192         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
193         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
194         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
195         check_added_monitors!(nodes[1], 1);
196
197         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
198         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
199         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
200         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
201         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
202         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
203         assert!(bs_update.update_fee.is_none()); // (4)
204         check_added_monitors!(nodes[1], 1);
205
206         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
207         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
208         assert!(as_update.update_add_htlcs.is_empty()); // (5)
209         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
210         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
211         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
212         assert!(as_update.update_fee.is_none()); // (5)
213         check_added_monitors!(nodes[0], 1);
214
215         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
216         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
217         // only (6) so get_event_msg's assert(len == 1) passes
218         check_added_monitors!(nodes[0], 1);
219
220         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
221         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
222         check_added_monitors!(nodes[1], 1);
223
224         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
225         check_added_monitors!(nodes[0], 1);
226
227         let events_2 = nodes[0].node.get_and_clear_pending_events();
228         assert_eq!(events_2.len(), 1);
229         match events_2[0] {
230                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
231                 _ => panic!("Unexpected event"),
232         }
233
234         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
235         check_added_monitors!(nodes[1], 1);
236 }
237
238 #[test]
239 fn test_update_fee_unordered_raa() {
240         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
241         // crash in an earlier version of the update_fee patch)
242         let chanmon_cfgs = create_chanmon_cfgs(2);
243         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
244         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
245         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
246         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
247         let channel_id = chan.2;
248         let logger = test_utils::TestLogger::new();
249
250         // balancing
251         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
252
253         // First nodes[0] generates an update_fee
254         nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
255         check_added_monitors!(nodes[0], 1);
256
257         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
258         assert_eq!(events_0.len(), 1);
259         let update_msg = match events_0[0] { // (1)
260                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
261                         update_fee.as_ref()
262                 },
263                 _ => panic!("Unexpected event"),
264         };
265
266         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
267
268         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
269         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
270         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
271         nodes[1].node.send_payment(&get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV, &logger).unwrap(), our_payment_hash, &None).unwrap();
272         check_added_monitors!(nodes[1], 1);
273
274         let payment_event = {
275                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
276                 assert_eq!(events_1.len(), 1);
277                 SendEvent::from_event(events_1.remove(0))
278         };
279         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
280         assert_eq!(payment_event.msgs.len(), 1);
281
282         // ...now when the messages get delivered everyone should be happy
283         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
284         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
285         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
286         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
287         check_added_monitors!(nodes[0], 1);
288
289         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
290         check_added_monitors!(nodes[1], 1);
291
292         // We can't continue, sadly, because our (1) now has a bogus signature
293 }
294
295 #[test]
296 fn test_multi_flight_update_fee() {
297         let chanmon_cfgs = create_chanmon_cfgs(2);
298         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
299         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
300         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
301         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
302         let channel_id = chan.2;
303
304         // A                                        B
305         // update_fee/commitment_signed          ->
306         //                                       .- send (1) RAA and (2) commitment_signed
307         // update_fee (never committed)          ->
308         // (3) update_fee                        ->
309         // We have to manually generate the above update_fee, it is allowed by the protocol but we
310         // don't track which updates correspond to which revoke_and_ack responses so we're in
311         // AwaitingRAA mode and will not generate the update_fee yet.
312         //                                       <- (1) RAA delivered
313         // (3) is generated and send (4) CS      -.
314         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
315         // know the per_commitment_point to use for it.
316         //                                       <- (2) commitment_signed delivered
317         // revoke_and_ack                        ->
318         //                                          B should send no response here
319         // (4) commitment_signed delivered       ->
320         //                                       <- RAA/commitment_signed delivered
321         // revoke_and_ack                        ->
322
323         // First nodes[0] generates an update_fee
324         let initial_feerate = get_feerate!(nodes[0], channel_id);
325         nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
326         check_added_monitors!(nodes[0], 1);
327
328         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
329         assert_eq!(events_0.len(), 1);
330         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
331                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
332                         (update_fee.as_ref().unwrap(), commitment_signed)
333                 },
334                 _ => panic!("Unexpected event"),
335         };
336
337         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
338         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
339         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
340         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
341         check_added_monitors!(nodes[1], 1);
342
343         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
344         // transaction:
345         nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
346         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
347         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
348
349         // Create the (3) update_fee message that nodes[0] will generate before it does...
350         let mut update_msg_2 = msgs::UpdateFee {
351                 channel_id: update_msg_1.channel_id.clone(),
352                 feerate_per_kw: (initial_feerate + 30) as u32,
353         };
354
355         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
356
357         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
358         // Deliver (3)
359         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
360
361         // Deliver (1), generating (3) and (4)
362         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
363         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
364         check_added_monitors!(nodes[0], 1);
365         assert!(as_second_update.update_add_htlcs.is_empty());
366         assert!(as_second_update.update_fulfill_htlcs.is_empty());
367         assert!(as_second_update.update_fail_htlcs.is_empty());
368         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
369         // Check that the update_fee newly generated matches what we delivered:
370         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
371         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
372
373         // Deliver (2) commitment_signed
374         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
375         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
376         check_added_monitors!(nodes[0], 1);
377         // No commitment_signed so get_event_msg's assert(len == 1) passes
378
379         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
380         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
381         check_added_monitors!(nodes[1], 1);
382
383         // Delever (4)
384         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
385         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
386         check_added_monitors!(nodes[1], 1);
387
388         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
389         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
390         check_added_monitors!(nodes[0], 1);
391
392         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
393         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
394         // No commitment_signed so get_event_msg's assert(len == 1) passes
395         check_added_monitors!(nodes[0], 1);
396
397         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
398         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
399         check_added_monitors!(nodes[1], 1);
400 }
401
402 #[test]
403 fn test_1_conf_open() {
404         // Previously, if the minium_depth config was set to 1, we'd never send a funding_locked. This
405         // tests that we properly send one in that case.
406         let mut alice_config = UserConfig::default();
407         alice_config.own_channel_config.minimum_depth = 1;
408         alice_config.channel_options.announced_channel = true;
409         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
410         let mut bob_config = UserConfig::default();
411         bob_config.own_channel_config.minimum_depth = 1;
412         bob_config.channel_options.announced_channel = true;
413         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
414         let chanmon_cfgs = create_chanmon_cfgs(2);
415         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
416         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(alice_config), Some(bob_config)]);
417         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
418
419         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
420         assert!(nodes[0].chain_monitor.does_match_tx(&tx));
421         assert!(nodes[1].chain_monitor.does_match_tx(&tx));
422
423         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
424         nodes[1].block_notifier.block_connected_checked(&header, 1, &[&tx; 1], &[tx.version as usize; 1]);
425         nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendFundingLocked, nodes[0].node.get_our_node_id()));
426
427         nodes[0].block_notifier.block_connected_checked(&header, 1, &[&tx; 1], &[tx.version as usize; 1]);
428         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
429         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
430
431         for node in nodes {
432                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
433                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
434                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
435         }
436 }
437
438 fn do_test_sanity_on_in_flight_opens(steps: u8) {
439         // Previously, we had issues deserializing channels when we hadn't connected the first block
440         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
441         // serialization round-trips and simply do steps towards opening a channel and then drop the
442         // Node objects.
443
444         let chanmon_cfgs = create_chanmon_cfgs(2);
445         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
446         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
447         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
448
449         if steps & 0b1000_0000 != 0{
450                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
451                 nodes[0].block_notifier.block_connected_checked(&header, 1, &Vec::new(), &[0; 0]);
452                 nodes[1].block_notifier.block_connected_checked(&header, 1, &Vec::new(), &[0; 0]);
453         }
454
455         if steps & 0x0f == 0 { return; }
456         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
457         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
458
459         if steps & 0x0f == 1 { return; }
460         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
461         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
462
463         if steps & 0x0f == 2 { return; }
464         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
465
466         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
467
468         if steps & 0x0f == 3 { return; }
469         nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
470         check_added_monitors!(nodes[0], 0);
471         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
472
473         if steps & 0x0f == 4 { return; }
474         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
475         {
476                 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
477                 assert_eq!(added_monitors.len(), 1);
478                 assert_eq!(added_monitors[0].0, funding_output);
479                 added_monitors.clear();
480         }
481         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
482
483         if steps & 0x0f == 5 { return; }
484         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
485         {
486                 let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
487                 assert_eq!(added_monitors.len(), 1);
488                 assert_eq!(added_monitors[0].0, funding_output);
489                 added_monitors.clear();
490         }
491
492         let events_4 = nodes[0].node.get_and_clear_pending_events();
493         assert_eq!(events_4.len(), 1);
494         match events_4[0] {
495                 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
496                         assert_eq!(user_channel_id, 42);
497                         assert_eq!(*funding_txo, funding_output);
498                 },
499                 _ => panic!("Unexpected event"),
500         };
501
502         if steps & 0x0f == 6 { return; }
503         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx);
504
505         if steps & 0x0f == 7 { return; }
506         confirm_transaction(&nodes[0].block_notifier, &nodes[0].chain_monitor, &tx, tx.version);
507         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
508 }
509
510 #[test]
511 fn test_sanity_on_in_flight_opens() {
512         do_test_sanity_on_in_flight_opens(0);
513         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
514         do_test_sanity_on_in_flight_opens(1);
515         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
516         do_test_sanity_on_in_flight_opens(2);
517         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
518         do_test_sanity_on_in_flight_opens(3);
519         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
520         do_test_sanity_on_in_flight_opens(4);
521         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
522         do_test_sanity_on_in_flight_opens(5);
523         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
524         do_test_sanity_on_in_flight_opens(6);
525         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
526         do_test_sanity_on_in_flight_opens(7);
527         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
528         do_test_sanity_on_in_flight_opens(8);
529         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
530 }
531
532 #[test]
533 fn test_update_fee_vanilla() {
534         let chanmon_cfgs = create_chanmon_cfgs(2);
535         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
536         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
537         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
538         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
539         let channel_id = chan.2;
540
541         let feerate = get_feerate!(nodes[0], channel_id);
542         nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
543         check_added_monitors!(nodes[0], 1);
544
545         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
546         assert_eq!(events_0.len(), 1);
547         let (update_msg, commitment_signed) = match events_0[0] {
548                         MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
549                         (update_fee.as_ref(), commitment_signed)
550                 },
551                 _ => panic!("Unexpected event"),
552         };
553         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
554
555         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
556         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
557         check_added_monitors!(nodes[1], 1);
558
559         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
560         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
561         check_added_monitors!(nodes[0], 1);
562
563         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
564         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
565         // No commitment_signed so get_event_msg's assert(len == 1) passes
566         check_added_monitors!(nodes[0], 1);
567
568         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
569         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
570         check_added_monitors!(nodes[1], 1);
571 }
572
573 #[test]
574 fn test_update_fee_that_funder_cannot_afford() {
575         let chanmon_cfgs = create_chanmon_cfgs(2);
576         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
577         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
578         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
579         let channel_value = 1888;
580         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000, InitFeatures::known(), InitFeatures::known());
581         let channel_id = chan.2;
582
583         let feerate = 260;
584         nodes[0].node.update_fee(channel_id, feerate).unwrap();
585         check_added_monitors!(nodes[0], 1);
586         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
587
588         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
589
590         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
591
592         //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
593         //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
594         {
595                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
596
597                 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
598                 let num_htlcs = commitment_tx.output.len() - 2;
599                 let total_fee: u64 = feerate as u64 * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
600                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
601                 actual_fee = channel_value - actual_fee;
602                 assert_eq!(total_fee, actual_fee);
603         }
604
605         //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
606         //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
607         nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
608         check_added_monitors!(nodes[0], 1);
609
610         let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
611
612         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap());
613
614         //While producing the commitment_signed response after handling a received update_fee request the
615         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
616         //Should produce and error.
617         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed);
618         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
619         check_added_monitors!(nodes[1], 1);
620         check_closed_broadcast!(nodes[1], true);
621 }
622
623 #[test]
624 fn test_update_fee_with_fundee_update_add_htlc() {
625         let chanmon_cfgs = create_chanmon_cfgs(2);
626         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
627         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
628         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
629         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
630         let channel_id = chan.2;
631         let logger = test_utils::TestLogger::new();
632
633         // balancing
634         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
635
636         let feerate = get_feerate!(nodes[0], channel_id);
637         nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
638         check_added_monitors!(nodes[0], 1);
639
640         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
641         assert_eq!(events_0.len(), 1);
642         let (update_msg, commitment_signed) = match events_0[0] {
643                         MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
644                         (update_fee.as_ref(), commitment_signed)
645                 },
646                 _ => panic!("Unexpected event"),
647         };
648         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
649         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
650         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
651         check_added_monitors!(nodes[1], 1);
652
653         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
654         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
655         let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, &Vec::new(), 800000, TEST_FINAL_CLTV, &logger).unwrap();
656
657         // nothing happens since node[1] is in AwaitingRemoteRevoke
658         nodes[1].node.send_payment(&route, our_payment_hash, &None).unwrap();
659         {
660                 let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
661                 assert_eq!(added_monitors.len(), 0);
662                 added_monitors.clear();
663         }
664         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
665         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
666         // node[1] has nothing to do
667
668         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
669         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
670         check_added_monitors!(nodes[0], 1);
671
672         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
673         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
674         // No commitment_signed so get_event_msg's assert(len == 1) passes
675         check_added_monitors!(nodes[0], 1);
676         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
677         check_added_monitors!(nodes[1], 1);
678         // AwaitingRemoteRevoke ends here
679
680         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
681         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
682         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
683         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
684         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
685         assert_eq!(commitment_update.update_fee.is_none(), true);
686
687         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
688         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
689         check_added_monitors!(nodes[0], 1);
690         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
691
692         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
693         check_added_monitors!(nodes[1], 1);
694         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
695
696         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
697         check_added_monitors!(nodes[1], 1);
698         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
699         // No commitment_signed so get_event_msg's assert(len == 1) passes
700
701         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
702         check_added_monitors!(nodes[0], 1);
703         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
704
705         expect_pending_htlcs_forwardable!(nodes[0]);
706
707         let events = nodes[0].node.get_and_clear_pending_events();
708         assert_eq!(events.len(), 1);
709         match events[0] {
710                 Event::PaymentReceived { .. } => { },
711                 _ => panic!("Unexpected event"),
712         };
713
714         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage, 800_000);
715
716         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000, 800_000);
717         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000, 800_000);
718         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
719 }
720
721 #[test]
722 fn test_update_fee() {
723         let chanmon_cfgs = create_chanmon_cfgs(2);
724         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
725         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
726         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
727         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
728         let channel_id = chan.2;
729
730         // A                                        B
731         // (1) update_fee/commitment_signed      ->
732         //                                       <- (2) revoke_and_ack
733         //                                       .- send (3) commitment_signed
734         // (4) update_fee/commitment_signed      ->
735         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
736         //                                       <- (3) commitment_signed delivered
737         // send (6) revoke_and_ack               -.
738         //                                       <- (5) deliver revoke_and_ack
739         // (6) deliver revoke_and_ack            ->
740         //                                       .- send (7) commitment_signed in response to (4)
741         //                                       <- (7) deliver commitment_signed
742         // revoke_and_ack                        ->
743
744         // Create and deliver (1)...
745         let feerate = get_feerate!(nodes[0], channel_id);
746         nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
747         check_added_monitors!(nodes[0], 1);
748
749         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
750         assert_eq!(events_0.len(), 1);
751         let (update_msg, commitment_signed) = match events_0[0] {
752                         MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
753                         (update_fee.as_ref(), commitment_signed)
754                 },
755                 _ => panic!("Unexpected event"),
756         };
757         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
758
759         // Generate (2) and (3):
760         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
761         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
762         check_added_monitors!(nodes[1], 1);
763
764         // Deliver (2):
765         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
766         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
767         check_added_monitors!(nodes[0], 1);
768
769         // Create and deliver (4)...
770         nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
771         check_added_monitors!(nodes[0], 1);
772         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
773         assert_eq!(events_0.len(), 1);
774         let (update_msg, commitment_signed) = match events_0[0] {
775                         MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
776                         (update_fee.as_ref(), commitment_signed)
777                 },
778                 _ => panic!("Unexpected event"),
779         };
780
781         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
782         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
783         check_added_monitors!(nodes[1], 1);
784         // ... creating (5)
785         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
786         // No commitment_signed so get_event_msg's assert(len == 1) passes
787
788         // Handle (3), creating (6):
789         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
790         check_added_monitors!(nodes[0], 1);
791         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
792         // No commitment_signed so get_event_msg's assert(len == 1) passes
793
794         // Deliver (5):
795         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
796         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
797         check_added_monitors!(nodes[0], 1);
798
799         // Deliver (6), creating (7):
800         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
801         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
802         assert!(commitment_update.update_add_htlcs.is_empty());
803         assert!(commitment_update.update_fulfill_htlcs.is_empty());
804         assert!(commitment_update.update_fail_htlcs.is_empty());
805         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
806         assert!(commitment_update.update_fee.is_none());
807         check_added_monitors!(nodes[1], 1);
808
809         // Deliver (7)
810         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
811         check_added_monitors!(nodes[0], 1);
812         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
813         // No commitment_signed so get_event_msg's assert(len == 1) passes
814
815         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
816         check_added_monitors!(nodes[1], 1);
817         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
818
819         assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
820         assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
821         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
822 }
823
824 #[test]
825 fn pre_funding_lock_shutdown_test() {
826         // Test sending a shutdown prior to funding_locked after funding generation
827         let chanmon_cfgs = create_chanmon_cfgs(2);
828         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
829         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
830         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
831         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0, InitFeatures::known(), InitFeatures::known());
832         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
833         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![tx.clone()]}, 1);
834         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![tx.clone()]}, 1);
835
836         nodes[0].node.close_channel(&OutPoint { txid: tx.txid(), index: 0 }.to_channel_id()).unwrap();
837         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
838         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
839         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
840         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
841
842         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
843         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
844         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
845         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
846         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
847         assert!(node_0_none.is_none());
848
849         assert!(nodes[0].node.list_channels().is_empty());
850         assert!(nodes[1].node.list_channels().is_empty());
851 }
852
853 #[test]
854 fn updates_shutdown_wait() {
855         // Test sending a shutdown with outstanding updates pending
856         let chanmon_cfgs = create_chanmon_cfgs(3);
857         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
858         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
859         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
860         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
861         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
862         let logger = test_utils::TestLogger::new();
863
864         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
865
866         nodes[0].node.close_channel(&chan_1.2).unwrap();
867         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
868         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
869         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
870         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
871
872         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
873         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
874
875         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
876
877         let net_graph_msg_handler0 = &nodes[0].net_graph_msg_handler;
878         let net_graph_msg_handler1 = &nodes[1].net_graph_msg_handler;
879         let route_1 = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler0.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
880         let route_2 = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler1.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
881         unwrap_send_err!(nodes[0].node.send_payment(&route_1, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
882         unwrap_send_err!(nodes[1].node.send_payment(&route_2, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
883
884         assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
885         check_added_monitors!(nodes[2], 1);
886         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
887         assert!(updates.update_add_htlcs.is_empty());
888         assert!(updates.update_fail_htlcs.is_empty());
889         assert!(updates.update_fail_malformed_htlcs.is_empty());
890         assert!(updates.update_fee.is_none());
891         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
892         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
893         check_added_monitors!(nodes[1], 1);
894         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
895         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
896
897         assert!(updates_2.update_add_htlcs.is_empty());
898         assert!(updates_2.update_fail_htlcs.is_empty());
899         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
900         assert!(updates_2.update_fee.is_none());
901         assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
902         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
903         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
904
905         let events = nodes[0].node.get_and_clear_pending_events();
906         assert_eq!(events.len(), 1);
907         match events[0] {
908                 Event::PaymentSent { ref payment_preimage } => {
909                         assert_eq!(our_payment_preimage, *payment_preimage);
910                 },
911                 _ => panic!("Unexpected event"),
912         }
913
914         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
915         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
916         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
917         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
918         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
919         assert!(node_0_none.is_none());
920
921         assert!(nodes[0].node.list_channels().is_empty());
922
923         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
924         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
925         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
926         assert!(nodes[1].node.list_channels().is_empty());
927         assert!(nodes[2].node.list_channels().is_empty());
928 }
929
930 #[test]
931 fn htlc_fail_async_shutdown() {
932         // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
933         let chanmon_cfgs = create_chanmon_cfgs(3);
934         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
935         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
936         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
937         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
938         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
939         let logger = test_utils::TestLogger::new();
940
941         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
942         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
943         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
944         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
945         check_added_monitors!(nodes[0], 1);
946         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
947         assert_eq!(updates.update_add_htlcs.len(), 1);
948         assert!(updates.update_fulfill_htlcs.is_empty());
949         assert!(updates.update_fail_htlcs.is_empty());
950         assert!(updates.update_fail_malformed_htlcs.is_empty());
951         assert!(updates.update_fee.is_none());
952
953         nodes[1].node.close_channel(&chan_1.2).unwrap();
954         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
955         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
956         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
957
958         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
959         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
960         check_added_monitors!(nodes[1], 1);
961         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
962         commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
963
964         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
965         assert!(updates_2.update_add_htlcs.is_empty());
966         assert!(updates_2.update_fulfill_htlcs.is_empty());
967         assert_eq!(updates_2.update_fail_htlcs.len(), 1);
968         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
969         assert!(updates_2.update_fee.is_none());
970
971         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]);
972         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
973
974         expect_payment_failed!(nodes[0], our_payment_hash, false);
975
976         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
977         assert_eq!(msg_events.len(), 2);
978         let node_0_closing_signed = match msg_events[0] {
979                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
980                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
981                         (*msg).clone()
982                 },
983                 _ => panic!("Unexpected event"),
984         };
985         match msg_events[1] {
986                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
987                         assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
988                 },
989                 _ => panic!("Unexpected event"),
990         }
991
992         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
993         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
994         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
995         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
996         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
997         assert!(node_0_none.is_none());
998
999         assert!(nodes[0].node.list_channels().is_empty());
1000
1001         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1002         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1003         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1004         assert!(nodes[1].node.list_channels().is_empty());
1005         assert!(nodes[2].node.list_channels().is_empty());
1006 }
1007
1008 fn do_test_shutdown_rebroadcast(recv_count: u8) {
1009         // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
1010         // messages delivered prior to disconnect
1011         let chanmon_cfgs = create_chanmon_cfgs(3);
1012         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1013         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1014         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1015         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1016         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1017
1018         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
1019
1020         nodes[1].node.close_channel(&chan_1.2).unwrap();
1021         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1022         if recv_count > 0 {
1023                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
1024                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1025                 if recv_count > 1 {
1026                         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
1027                 }
1028         }
1029
1030         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1031         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1032
1033         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1034         let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1035         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1036         let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1037
1038         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish);
1039         let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1040         assert!(node_1_shutdown == node_1_2nd_shutdown);
1041
1042         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish);
1043         let node_0_2nd_shutdown = if recv_count > 0 {
1044                 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1045                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
1046                 node_0_2nd_shutdown
1047         } else {
1048                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1049                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
1050                 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
1051         };
1052         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown);
1053
1054         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1055         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1056
1057         assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
1058         check_added_monitors!(nodes[2], 1);
1059         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1060         assert!(updates.update_add_htlcs.is_empty());
1061         assert!(updates.update_fail_htlcs.is_empty());
1062         assert!(updates.update_fail_malformed_htlcs.is_empty());
1063         assert!(updates.update_fee.is_none());
1064         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
1065         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
1066         check_added_monitors!(nodes[1], 1);
1067         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1068         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
1069
1070         assert!(updates_2.update_add_htlcs.is_empty());
1071         assert!(updates_2.update_fail_htlcs.is_empty());
1072         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
1073         assert!(updates_2.update_fee.is_none());
1074         assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
1075         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
1076         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
1077
1078         let events = nodes[0].node.get_and_clear_pending_events();
1079         assert_eq!(events.len(), 1);
1080         match events[0] {
1081                 Event::PaymentSent { ref payment_preimage } => {
1082                         assert_eq!(our_payment_preimage, *payment_preimage);
1083                 },
1084                 _ => panic!("Unexpected event"),
1085         }
1086
1087         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1088         if recv_count > 0 {
1089                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
1090                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1091                 assert!(node_1_closing_signed.is_some());
1092         }
1093
1094         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1095         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1096
1097         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1098         let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1099         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1100         if recv_count == 0 {
1101                 // If all closing_signeds weren't delivered we can just resume where we left off...
1102                 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1103
1104                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish);
1105                 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1106                 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
1107
1108                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1109                 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1110                 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
1111
1112                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown);
1113                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1114
1115                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown);
1116                 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1117                 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
1118
1119                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed);
1120                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1121                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
1122                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1123                 assert!(node_0_none.is_none());
1124         } else {
1125                 // If one node, however, received + responded with an identical closing_signed we end
1126                 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
1127                 // There isn't really anything better we can do simply, but in the future we might
1128                 // explore storing a set of recently-closed channels that got disconnected during
1129                 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
1130                 // give our counterparty enough time to (potentially) broadcast a cooperative closing
1131                 // transaction.
1132                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1133
1134                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1135                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1136                 assert_eq!(msg_events.len(), 1);
1137                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
1138                         match action {
1139                                 &ErrorAction::SendErrorMessage { ref msg } => {
1140                                         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
1141                                         assert_eq!(msg.channel_id, chan_1.2);
1142                                 },
1143                                 _ => panic!("Unexpected event!"),
1144                         }
1145                 } else { panic!("Needed SendErrorMessage close"); }
1146
1147                 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
1148                 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
1149                 // closing_signed so we do it ourselves
1150                 check_closed_broadcast!(nodes[0], false);
1151                 check_added_monitors!(nodes[0], 1);
1152         }
1153
1154         assert!(nodes[0].node.list_channels().is_empty());
1155
1156         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1157         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1158         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1159         assert!(nodes[1].node.list_channels().is_empty());
1160         assert!(nodes[2].node.list_channels().is_empty());
1161 }
1162
1163 #[test]
1164 fn test_shutdown_rebroadcast() {
1165         do_test_shutdown_rebroadcast(0);
1166         do_test_shutdown_rebroadcast(1);
1167         do_test_shutdown_rebroadcast(2);
1168 }
1169
1170 #[test]
1171 fn fake_network_test() {
1172         // Simple test which builds a network of ChannelManagers, connects them to each other, and
1173         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
1174         let chanmon_cfgs = create_chanmon_cfgs(4);
1175         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1176         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1177         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1178
1179         // Create some initial channels
1180         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1181         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1182         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1183
1184         // Rebalance the network a bit by relaying one payment through all the channels...
1185         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1186         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1187         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1188         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1189
1190         // Send some more payments
1191         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000, 1_000_000);
1192         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000, 1_000_000);
1193         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000, 1_000_000);
1194
1195         // Test failure packets
1196         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1197         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1198
1199         // Add a new channel that skips 3
1200         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1201
1202         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000, 1_000_000);
1203         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000, 1_000_000);
1204         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1205         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1206         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1207         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1208         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1209
1210         // Do some rebalance loop payments, simultaneously
1211         let mut hops = Vec::with_capacity(3);
1212         hops.push(RouteHop {
1213                 pubkey: nodes[2].node.get_our_node_id(),
1214                 node_features: NodeFeatures::empty(),
1215                 short_channel_id: chan_2.0.contents.short_channel_id,
1216                 channel_features: ChannelFeatures::empty(),
1217                 fee_msat: 0,
1218                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1219         });
1220         hops.push(RouteHop {
1221                 pubkey: nodes[3].node.get_our_node_id(),
1222                 node_features: NodeFeatures::empty(),
1223                 short_channel_id: chan_3.0.contents.short_channel_id,
1224                 channel_features: ChannelFeatures::empty(),
1225                 fee_msat: 0,
1226                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1227         });
1228         hops.push(RouteHop {
1229                 pubkey: nodes[1].node.get_our_node_id(),
1230                 node_features: NodeFeatures::empty(),
1231                 short_channel_id: chan_4.0.contents.short_channel_id,
1232                 channel_features: ChannelFeatures::empty(),
1233                 fee_msat: 1000000,
1234                 cltv_expiry_delta: TEST_FINAL_CLTV,
1235         });
1236         hops[1].fee_msat = chan_4.1.contents.fee_base_msat as u64 + chan_4.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1237         hops[0].fee_msat = chan_3.0.contents.fee_base_msat as u64 + chan_3.0.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1238         let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1239
1240         let mut hops = Vec::with_capacity(3);
1241         hops.push(RouteHop {
1242                 pubkey: nodes[3].node.get_our_node_id(),
1243                 node_features: NodeFeatures::empty(),
1244                 short_channel_id: chan_4.0.contents.short_channel_id,
1245                 channel_features: ChannelFeatures::empty(),
1246                 fee_msat: 0,
1247                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1248         });
1249         hops.push(RouteHop {
1250                 pubkey: nodes[2].node.get_our_node_id(),
1251                 node_features: NodeFeatures::empty(),
1252                 short_channel_id: chan_3.0.contents.short_channel_id,
1253                 channel_features: ChannelFeatures::empty(),
1254                 fee_msat: 0,
1255                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1256         });
1257         hops.push(RouteHop {
1258                 pubkey: nodes[1].node.get_our_node_id(),
1259                 node_features: NodeFeatures::empty(),
1260                 short_channel_id: chan_2.0.contents.short_channel_id,
1261                 channel_features: ChannelFeatures::empty(),
1262                 fee_msat: 1000000,
1263                 cltv_expiry_delta: TEST_FINAL_CLTV,
1264         });
1265         hops[1].fee_msat = chan_2.1.contents.fee_base_msat as u64 + chan_2.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1266         hops[0].fee_msat = chan_3.1.contents.fee_base_msat as u64 + chan_3.1.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1267         let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1268
1269         // Claim the rebalances...
1270         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1271         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1, 1_000_000);
1272
1273         // Add a duplicate new channel from 2 to 4
1274         let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1275
1276         // Send some payments across both channels
1277         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1278         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1279         let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1280
1281
1282         route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1283         let events = nodes[0].node.get_and_clear_pending_msg_events();
1284         assert_eq!(events.len(), 0);
1285         nodes[0].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), regex::Regex::new(r"Cannot send value that would put us over the max HTLC value in flight our peer will accept \(\d+\)").unwrap(), 1);
1286
1287         //TODO: Test that routes work again here as we've been notified that the channel is full
1288
1289         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3, 3_000_000);
1290         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4, 3_000_000);
1291         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5, 3_000_000);
1292
1293         // Close down the channels...
1294         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1295         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1296         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1297         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1298         close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1299 }
1300
1301 #[test]
1302 fn holding_cell_htlc_counting() {
1303         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1304         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1305         // commitment dance rounds.
1306         let chanmon_cfgs = create_chanmon_cfgs(3);
1307         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1308         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1309         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1310         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1311         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1312         let logger = test_utils::TestLogger::new();
1313
1314         let mut payments = Vec::new();
1315         for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1316                 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1317                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1318                 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1319                 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
1320                 payments.push((payment_preimage, payment_hash));
1321         }
1322         check_added_monitors!(nodes[1], 1);
1323
1324         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1325         assert_eq!(events.len(), 1);
1326         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1327         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1328
1329         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1330         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1331         // another HTLC.
1332         let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
1333         {
1334                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1335                 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1336                 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &None), true, APIError::ChannelUnavailable { ref err },
1337                         assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1338                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1339                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1340         }
1341
1342         // This should also be true if we try to forward a payment.
1343         let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
1344         {
1345                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1346                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1347                 nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
1348                 check_added_monitors!(nodes[0], 1);
1349         }
1350
1351         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1352         assert_eq!(events.len(), 1);
1353         let payment_event = SendEvent::from_event(events.pop().unwrap());
1354         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1355
1356         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1357         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1358         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1359         // fails), the second will process the resulting failure and fail the HTLC backward.
1360         expect_pending_htlcs_forwardable!(nodes[1]);
1361         expect_pending_htlcs_forwardable!(nodes[1]);
1362         check_added_monitors!(nodes[1], 1);
1363
1364         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1365         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1366         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1367
1368         let events = nodes[0].node.get_and_clear_pending_msg_events();
1369         assert_eq!(events.len(), 1);
1370         match events[0] {
1371                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
1372                         assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
1373                 },
1374                 _ => panic!("Unexpected event"),
1375         }
1376
1377         expect_payment_failed!(nodes[0], payment_hash_2, false);
1378
1379         // Now forward all the pending HTLCs and claim them back
1380         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1381         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1382         check_added_monitors!(nodes[2], 1);
1383
1384         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1385         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1386         check_added_monitors!(nodes[1], 1);
1387         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1388
1389         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1390         check_added_monitors!(nodes[1], 1);
1391         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1392
1393         for ref update in as_updates.update_add_htlcs.iter() {
1394                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1395         }
1396         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1397         check_added_monitors!(nodes[2], 1);
1398         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1399         check_added_monitors!(nodes[2], 1);
1400         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1401
1402         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1403         check_added_monitors!(nodes[1], 1);
1404         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1405         check_added_monitors!(nodes[1], 1);
1406         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1407
1408         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1409         check_added_monitors!(nodes[2], 1);
1410
1411         expect_pending_htlcs_forwardable!(nodes[2]);
1412
1413         let events = nodes[2].node.get_and_clear_pending_events();
1414         assert_eq!(events.len(), payments.len());
1415         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1416                 match event {
1417                         &Event::PaymentReceived { ref payment_hash, .. } => {
1418                                 assert_eq!(*payment_hash, *hash);
1419                         },
1420                         _ => panic!("Unexpected event"),
1421                 };
1422         }
1423
1424         for (preimage, _) in payments.drain(..) {
1425                 claim_payment(&nodes[1], &[&nodes[2]], preimage, 100_000);
1426         }
1427
1428         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000, 1_000_000);
1429 }
1430
1431 #[test]
1432 fn duplicate_htlc_test() {
1433         // Test that we accept duplicate payment_hash HTLCs across the network and that
1434         // claiming/failing them are all separate and don't affect each other
1435         let chanmon_cfgs = create_chanmon_cfgs(6);
1436         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1437         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1438         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1439
1440         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1441         create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1442         create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1443         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1444         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1445         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1446
1447         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1448
1449         *nodes[0].network_payment_count.borrow_mut() -= 1;
1450         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1451
1452         *nodes[0].network_payment_count.borrow_mut() -= 1;
1453         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1454
1455         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage, 1_000_000);
1456         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1457         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage, 1_000_000);
1458 }
1459
1460 #[test]
1461 fn test_duplicate_htlc_different_direction_onchain() {
1462         // Test that ChannelMonitor doesn't generate 2 preimage txn
1463         // when we have 2 HTLCs with same preimage that go across a node
1464         // in opposite directions.
1465         let chanmon_cfgs = create_chanmon_cfgs(2);
1466         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1467         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1468         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1469
1470         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1471         let logger = test_utils::TestLogger::new();
1472
1473         // balancing
1474         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
1475
1476         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1477
1478         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1479         let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, &Vec::new(), 800_000, TEST_FINAL_CLTV, &logger).unwrap();
1480         send_along_route_with_hash(&nodes[1], route, &vec!(&nodes[0])[..], 800_000, payment_hash);
1481
1482         // Provide preimage to node 0 by claiming payment
1483         nodes[0].node.claim_funds(payment_preimage, &None, 800_000);
1484         check_added_monitors!(nodes[0], 1);
1485
1486         // Broadcast node 1 commitment txn
1487         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1488
1489         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1490         let mut has_both_htlcs = 0; // check htlcs match ones committed
1491         for outp in remote_txn[0].output.iter() {
1492                 if outp.value == 800_000 / 1000 {
1493                         has_both_htlcs += 1;
1494                 } else if outp.value == 900_000 / 1000 {
1495                         has_both_htlcs += 1;
1496                 }
1497         }
1498         assert_eq!(has_both_htlcs, 2);
1499
1500         let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1501         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
1502         check_added_monitors!(nodes[0], 1);
1503
1504         // Check we only broadcast 1 timeout tx
1505         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1506         let htlc_pair = if claim_txn[0].output[0].value == 800_000 / 1000 { (claim_txn[0].clone(), claim_txn[1].clone()) } else { (claim_txn[1].clone(), claim_txn[0].clone()) };
1507         assert_eq!(claim_txn.len(), 5);
1508         check_spends!(claim_txn[2], chan_1.3);
1509         check_spends!(claim_txn[3], claim_txn[2]);
1510         assert_eq!(htlc_pair.0.input.len(), 1);
1511         assert_eq!(htlc_pair.0.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1512         check_spends!(htlc_pair.0, remote_txn[0]);
1513         assert_eq!(htlc_pair.1.input.len(), 1);
1514         assert_eq!(htlc_pair.1.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1515         check_spends!(htlc_pair.1, remote_txn[0]);
1516
1517         let events = nodes[0].node.get_and_clear_pending_msg_events();
1518         assert_eq!(events.len(), 2);
1519         for e in events {
1520                 match e {
1521                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1522                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
1523                                 assert!(update_add_htlcs.is_empty());
1524                                 assert!(update_fail_htlcs.is_empty());
1525                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1526                                 assert!(update_fail_malformed_htlcs.is_empty());
1527                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1528                         },
1529                         _ => panic!("Unexpected event"),
1530                 }
1531         }
1532 }
1533
1534 #[test]
1535 fn test_basic_channel_reserve() {
1536         let chanmon_cfgs = create_chanmon_cfgs(2);
1537         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1538         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1539         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1540         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1541         let logger = test_utils::TestLogger::new();
1542
1543         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1544         let channel_reserve = chan_stat.channel_reserve_msat;
1545
1546         // The 2* and +1 are for the fee spike reserve.
1547         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
1548         let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1);
1549         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1550         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1551         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), max_can_send + 1, TEST_FINAL_CLTV, &logger).unwrap();
1552         let err = nodes[0].node.send_payment(&route, our_payment_hash, &None).err().unwrap();
1553         match err {
1554                 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1555                         match &fails[0] {
1556                                 &APIError::ChannelUnavailable{ref err} =>
1557                                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1558                                 _ => panic!("Unexpected error variant"),
1559                         }
1560                 },
1561                 _ => panic!("Unexpected error variant"),
1562         }
1563         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1564         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put our balance under counterparty-announced channel reserve value".to_string(), 1);
1565
1566         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send, max_can_send);
1567 }
1568
1569 #[test]
1570 fn test_fee_spike_violation_fails_htlc() {
1571         let chanmon_cfgs = create_chanmon_cfgs(2);
1572         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1573         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1574         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1575         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1576         let logger = test_utils::TestLogger::new();
1577
1578         macro_rules! get_route_and_payment_hash {
1579                 ($recv_value: expr) => {{
1580                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1581                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler.network_graph.read().unwrap();
1582                         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1583                         (route, payment_hash, payment_preimage)
1584                 }}
1585         };
1586
1587         let (route, payment_hash, _) = get_route_and_payment_hash!(3460001);
1588         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1589         let secp_ctx = Secp256k1::new();
1590         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1591
1592         let cur_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1593
1594         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1595         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &None, cur_height).unwrap();
1596         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1597         let msg = msgs::UpdateAddHTLC {
1598                 channel_id: chan.2,
1599                 htlc_id: 0,
1600                 amount_msat: htlc_msat,
1601                 payment_hash: payment_hash,
1602                 cltv_expiry: htlc_cltv,
1603                 onion_routing_packet: onion_packet,
1604         };
1605
1606         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1607
1608         // Now manually create the commitment_signed message corresponding to the update_add
1609         // nodes[0] just sent. In the code for construction of this message, "local" refers
1610         // to the sender of the message, and "remote" refers to the receiver.
1611
1612         let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1613
1614         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1615
1616         // Get the EnforcingChannelKeys for each channel, which will be used to (1) get the keys
1617         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1618         let (local_revocation_basepoint, local_htlc_basepoint, local_payment_point, local_secret, local_secret2) = {
1619                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1620                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1621                 let chan_keys = local_chan.get_keys();
1622                 let pubkeys = chan_keys.pubkeys();
1623                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint, pubkeys.payment_point,
1624                  chan_keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER), chan_keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2))
1625         };
1626         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_payment_point, remote_secret1) = {
1627                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1628                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1629                 let chan_keys = remote_chan.get_keys();
1630                 let pubkeys = chan_keys.pubkeys();
1631                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint, pubkeys.payment_point,
1632                  chan_keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1))
1633         };
1634
1635         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1636         let commitment_secret = SecretKey::from_slice(&remote_secret1).unwrap();
1637         let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &commitment_secret);
1638         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &per_commitment_point, &remote_delayed_payment_basepoint,
1639                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1640
1641         // Build the remote commitment transaction so we can sign it, and then later use the
1642         // signature for the commitment_signed message.
1643         let local_chan_balance = 1313;
1644         let static_payment_pk = local_payment_point.serialize();
1645         let remote_commit_tx_output = TxOut {
1646                                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0)
1647                                                              .push_slice(&WPubkeyHash::hash(&static_payment_pk)[..])
1648                                                              .into_script(),
1649                 value: local_chan_balance as u64
1650         };
1651
1652         let local_commit_tx_output = TxOut {
1653                 script_pubkey: chan_utils::get_revokeable_redeemscript(&commit_tx_keys.revocation_key,
1654                                                                                BREAKDOWN_TIMEOUT,
1655                                                                                &commit_tx_keys.broadcaster_delayed_payment_key).to_v0_p2wsh(),
1656                                 value: 95000,
1657         };
1658
1659         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1660                 offered: false,
1661                 amount_msat: 3460001,
1662                 cltv_expiry: htlc_cltv,
1663                 payment_hash: payment_hash,
1664                 transaction_output_index: Some(1),
1665         };
1666
1667         let htlc_output = TxOut {
1668                 script_pubkey: chan_utils::get_htlc_redeemscript(&accepted_htlc_info, &commit_tx_keys).to_v0_p2wsh(),
1669                 value: 3460001 / 1000
1670         };
1671
1672         let commit_tx_obscure_factor = {
1673                 let mut sha = Sha256::engine();
1674                 let remote_payment_point = &remote_payment_point.serialize();
1675                 sha.input(&local_payment_point.serialize());
1676                 sha.input(remote_payment_point);
1677                 let res = Sha256::from_engine(sha).into_inner();
1678
1679                 ((res[26] as u64) << 5*8) |
1680                 ((res[27] as u64) << 4*8) |
1681                 ((res[28] as u64) << 3*8) |
1682                 ((res[29] as u64) << 2*8) |
1683                 ((res[30] as u64) << 1*8) |
1684                 ((res[31] as u64) << 0*8)
1685         };
1686         let commitment_number = 1;
1687         let obscured_commitment_transaction_number = commit_tx_obscure_factor ^ commitment_number;
1688         let lock_time = ((0x20 as u32) << 8*3) | ((obscured_commitment_transaction_number & 0xffffffu64) as u32);
1689         let input = TxIn {
1690                 previous_output: BitcoinOutPoint { txid: chan.3.txid(), vout: 0 },
1691                 script_sig: Script::new(),
1692                 sequence: ((0x80 as u32) << 8*3) | ((obscured_commitment_transaction_number >> 3*8) as u32),
1693                 witness: Vec::new(),
1694         };
1695
1696         let commit_tx = Transaction {
1697                 version: 2,
1698                 lock_time,
1699                 input: vec![input],
1700                 output: vec![remote_commit_tx_output, htlc_output, local_commit_tx_output],
1701         };
1702         let res = {
1703                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1704                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1705                 let local_chan_keys = local_chan.get_keys();
1706                 let pre_commit_tx_keys = PreCalculatedTxCreationKeys::new(commit_tx_keys);
1707                 local_chan_keys.sign_counterparty_commitment(feerate_per_kw, &commit_tx, &pre_commit_tx_keys, &[&accepted_htlc_info], &secp_ctx).unwrap()
1708         };
1709
1710         let commit_signed_msg = msgs::CommitmentSigned {
1711                 channel_id: chan.2,
1712                 signature: res.0,
1713                 htlc_signatures: res.1
1714         };
1715
1716         // Send the commitment_signed message to the nodes[1].
1717         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1718         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1719
1720         // Send the RAA to nodes[1].
1721         let per_commitment_secret = local_secret;
1722         let next_secret = SecretKey::from_slice(&local_secret2).unwrap();
1723         let next_per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &next_secret);
1724         let raa_msg = msgs::RevokeAndACK{ channel_id: chan.2, per_commitment_secret, next_per_commitment_point};
1725         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1726
1727         let events = nodes[1].node.get_and_clear_pending_msg_events();
1728         assert_eq!(events.len(), 1);
1729         // Make sure the HTLC failed in the way we expect.
1730         match events[0] {
1731                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1732                         assert_eq!(update_fail_htlcs.len(), 1);
1733                         update_fail_htlcs[0].clone()
1734                 },
1735                 _ => panic!("Unexpected event"),
1736         };
1737         nodes[1].logger.assert_log("lightning::ln::channel".to_string(), "Attempting to fail HTLC due to fee spike buffer violation".to_string(), 1);
1738
1739         check_added_monitors!(nodes[1], 2);
1740 }
1741
1742 #[test]
1743 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1744         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1745         // Set the fee rate for the channel very high, to the point where the fundee
1746         // sending any amount would result in a channel reserve violation. In this test
1747         // we check that we would be prevented from sending an HTLC in this situation.
1748         chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1749         chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1750         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1751         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1752         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1753         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1754         let logger = test_utils::TestLogger::new();
1755
1756         macro_rules! get_route_and_payment_hash {
1757                 ($recv_value: expr) => {{
1758                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1759                         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1760                         let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes.first().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1761                         (route, payment_hash, payment_preimage)
1762                 }}
1763         };
1764
1765         let (route, our_payment_hash, _) = get_route_and_payment_hash!(1000);
1766         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1767                 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1768         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1769         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put counterparty balance under holder-announced channel reserve value".to_string(), 1);
1770 }
1771
1772 #[test]
1773 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1774         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1775         // Set the fee rate for the channel very high, to the point where the funder
1776         // receiving 1 update_add_htlc would result in them closing the channel due
1777         // to channel reserve violation. This close could also happen if the fee went
1778         // up a more realistic amount, but many HTLCs were outstanding at the time of
1779         // the update_add_htlc.
1780         chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1781         chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1782         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1783         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1784         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1785         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1786         let logger = test_utils::TestLogger::new();
1787
1788         macro_rules! get_route_and_payment_hash {
1789                 ($recv_value: expr) => {{
1790                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1791                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1792                         let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes.first().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1793                         (route, payment_hash, payment_preimage)
1794                 }}
1795         };
1796
1797         let (route, payment_hash, _) = get_route_and_payment_hash!(1000);
1798         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1799         let secp_ctx = Secp256k1::new();
1800         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1801         let cur_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1802         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1803         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 1000, &None, cur_height).unwrap();
1804         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1805         let msg = msgs::UpdateAddHTLC {
1806                 channel_id: chan.2,
1807                 htlc_id: 1,
1808                 amount_msat: htlc_msat + 1,
1809                 payment_hash: payment_hash,
1810                 cltv_expiry: htlc_cltv,
1811                 onion_routing_packet: onion_packet,
1812         };
1813
1814         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1815         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1816         nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value".to_string(), 1);
1817         assert_eq!(nodes[0].node.list_channels().len(), 0);
1818         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1819         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1820         check_added_monitors!(nodes[0], 1);
1821 }
1822
1823 #[test]
1824 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1825         let chanmon_cfgs = create_chanmon_cfgs(3);
1826         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1827         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1828         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1829         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1830         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1831         let logger = test_utils::TestLogger::new();
1832
1833         macro_rules! get_route_and_payment_hash {
1834                 ($recv_value: expr) => {{
1835                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1836                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1837                         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1838                         (route, payment_hash, payment_preimage)
1839                 }}
1840         };
1841
1842         let feemsat = 239;
1843         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1844         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1845         let feerate = get_feerate!(nodes[0], chan.2);
1846
1847         // Add a 2* and +1 for the fee spike reserve.
1848         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1);
1849         let recv_value_1 = (chan_stat.value_to_self_msat - chan_stat.channel_reserve_msat - total_routing_fee_msat - commit_tx_fee_2_htlc)/2;
1850         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1851
1852         // Add a pending HTLC.
1853         let (route_1, our_payment_hash_1, _) = get_route_and_payment_hash!(amt_msat_1);
1854         let payment_event_1 = {
1855                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
1856                 check_added_monitors!(nodes[0], 1);
1857
1858                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1859                 assert_eq!(events.len(), 1);
1860                 SendEvent::from_event(events.remove(0))
1861         };
1862         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1863
1864         // Attempt to trigger a channel reserve violation --> payment failure.
1865         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2);
1866         let recv_value_2 = chan_stat.value_to_self_msat - amt_msat_1 - chan_stat.channel_reserve_msat - total_routing_fee_msat - commit_tx_fee_2_htlcs + 1;
1867         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1868         let (route_2, _, _) = get_route_and_payment_hash!(amt_msat_2);
1869
1870         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1871         let secp_ctx = Secp256k1::new();
1872         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1873         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1874         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1875         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height).unwrap();
1876         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1877         let msg = msgs::UpdateAddHTLC {
1878                 channel_id: chan.2,
1879                 htlc_id: 1,
1880                 amount_msat: htlc_msat + 1,
1881                 payment_hash: our_payment_hash_1,
1882                 cltv_expiry: htlc_cltv,
1883                 onion_routing_packet: onion_packet,
1884         };
1885
1886         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1887         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1888         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1889         assert_eq!(nodes[1].node.list_channels().len(), 1);
1890         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1891         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1892         check_added_monitors!(nodes[1], 1);
1893 }
1894
1895 #[test]
1896 fn test_inbound_outbound_capacity_is_not_zero() {
1897         let chanmon_cfgs = create_chanmon_cfgs(2);
1898         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1899         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1900         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1901         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1902         let channels0 = node_chanmgrs[0].list_channels();
1903         let channels1 = node_chanmgrs[1].list_channels();
1904         assert_eq!(channels0.len(), 1);
1905         assert_eq!(channels1.len(), 1);
1906
1907         assert_eq!(channels0[0].inbound_capacity_msat, 95000000);
1908         assert_eq!(channels1[0].outbound_capacity_msat, 95000000);
1909
1910         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000);
1911         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000);
1912 }
1913
1914 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64) -> u64 {
1915         (COMMITMENT_TX_BASE_WEIGHT + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1916 }
1917
1918 #[test]
1919 fn test_channel_reserve_holding_cell_htlcs() {
1920         let chanmon_cfgs = create_chanmon_cfgs(3);
1921         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1922         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1923         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1924         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1925         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1926         let logger = test_utils::TestLogger::new();
1927
1928         let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1929         let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1930
1931         let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1932         let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1933
1934         macro_rules! get_route_and_payment_hash {
1935                 ($recv_value: expr) => {{
1936                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1937                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1938                         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1939                         (route, payment_hash, payment_preimage)
1940                 }}
1941         };
1942
1943         macro_rules! expect_forward {
1944                 ($node: expr) => {{
1945                         let mut events = $node.node.get_and_clear_pending_msg_events();
1946                         assert_eq!(events.len(), 1);
1947                         check_added_monitors!($node, 1);
1948                         let payment_event = SendEvent::from_event(events.remove(0));
1949                         payment_event
1950                 }}
1951         }
1952
1953         let feemsat = 239; // somehow we know?
1954         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1955         let feerate = get_feerate!(nodes[0], chan_1.2);
1956
1957         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1958
1959         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1960         {
1961                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
1962                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1963                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1964                         assert!(regex::Regex::new(r"Cannot send value that would put us over the max HTLC value in flight our peer will accept \(\d+\)").unwrap().is_match(err)));
1965                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1966                 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us over the max HTLC value in flight our peer will accept".to_string(), 1);
1967         }
1968
1969         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1970         // nodes[0]'s wealth
1971         loop {
1972                 let amt_msat = recv_value_0 + total_fee_msat;
1973                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1974                 // Also, ensure that each payment has enough to be over the dust limit to
1975                 // ensure it'll be included in each commit tx fee calculation.
1976                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1977                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1978                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1979                         break;
1980                 }
1981                 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0, recv_value_0);
1982
1983                 let (stat01_, stat11_, stat12_, stat22_) = (
1984                         get_channel_value_stat!(nodes[0], chan_1.2),
1985                         get_channel_value_stat!(nodes[1], chan_1.2),
1986                         get_channel_value_stat!(nodes[1], chan_2.2),
1987                         get_channel_value_stat!(nodes[2], chan_2.2),
1988                 );
1989
1990                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1991                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1992                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1993                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1994                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1995         }
1996
1997         // adding pending output.
1998         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1999         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
2000         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
2001         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
2002         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
2003         // cases where 1 msat over X amount will cause a payment failure, but anything less than
2004         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
2005         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
2006         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
2007         // policy.
2008         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1);
2009         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
2010         let amt_msat_1 = recv_value_1 + total_fee_msat;
2011
2012         let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
2013         let payment_event_1 = {
2014                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
2015                 check_added_monitors!(nodes[0], 1);
2016
2017                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2018                 assert_eq!(events.len(), 1);
2019                 SendEvent::from_event(events.remove(0))
2020         };
2021         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
2022
2023         // channel reserve test with htlc pending output > 0
2024         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
2025         {
2026                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
2027                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
2028                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
2029                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2030         }
2031
2032         // split the rest to test holding cell
2033         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
2034         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
2035         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
2036         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
2037         {
2038                 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
2039                 assert_eq!(stat.value_to_self_msat - (stat.pending_outbound_htlcs_amount_msat + recv_value_21 + recv_value_22 + total_fee_msat + total_fee_msat + commit_tx_fee_3_htlcs), stat.channel_reserve_msat);
2040         }
2041
2042         // now see if they go through on both sides
2043         let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
2044         // but this will stuck in the holding cell
2045         nodes[0].node.send_payment(&route_21, our_payment_hash_21, &None).unwrap();
2046         check_added_monitors!(nodes[0], 0);
2047         let events = nodes[0].node.get_and_clear_pending_events();
2048         assert_eq!(events.len(), 0);
2049
2050         // test with outbound holding cell amount > 0
2051         {
2052                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
2053                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
2054                         assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
2055                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2056                 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put our balance under counterparty-announced channel reserve value".to_string(), 2);
2057         }
2058
2059         let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
2060         // this will also stuck in the holding cell
2061         nodes[0].node.send_payment(&route_22, our_payment_hash_22, &None).unwrap();
2062         check_added_monitors!(nodes[0], 0);
2063         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
2064         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2065
2066         // flush the pending htlc
2067         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
2068         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2069         check_added_monitors!(nodes[1], 1);
2070
2071         // the pending htlc should be promoted to committed
2072         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
2073         check_added_monitors!(nodes[0], 1);
2074         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2075
2076         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
2077         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2078         // No commitment_signed so get_event_msg's assert(len == 1) passes
2079         check_added_monitors!(nodes[0], 1);
2080
2081         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
2082         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2083         check_added_monitors!(nodes[1], 1);
2084
2085         expect_pending_htlcs_forwardable!(nodes[1]);
2086
2087         let ref payment_event_11 = expect_forward!(nodes[1]);
2088         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
2089         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
2090
2091         expect_pending_htlcs_forwardable!(nodes[2]);
2092         expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
2093
2094         // flush the htlcs in the holding cell
2095         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
2096         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
2097         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
2098         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
2099         expect_pending_htlcs_forwardable!(nodes[1]);
2100
2101         let ref payment_event_3 = expect_forward!(nodes[1]);
2102         assert_eq!(payment_event_3.msgs.len(), 2);
2103         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
2104         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
2105
2106         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2107         expect_pending_htlcs_forwardable!(nodes[2]);
2108
2109         let events = nodes[2].node.get_and_clear_pending_events();
2110         assert_eq!(events.len(), 2);
2111         match events[0] {
2112                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2113                         assert_eq!(our_payment_hash_21, *payment_hash);
2114                         assert_eq!(*payment_secret, None);
2115                         assert_eq!(recv_value_21, amt);
2116                 },
2117                 _ => panic!("Unexpected event"),
2118         }
2119         match events[1] {
2120                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2121                         assert_eq!(our_payment_hash_22, *payment_hash);
2122                         assert_eq!(None, *payment_secret);
2123                         assert_eq!(recv_value_22, amt);
2124                 },
2125                 _ => panic!("Unexpected event"),
2126         }
2127
2128         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1, recv_value_1);
2129         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21, recv_value_21);
2130         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22, recv_value_22);
2131
2132         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1);
2133         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2134         {
2135                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_3 + 1);
2136                 let err = nodes[0].node.send_payment(&route, our_payment_hash, &None).err().unwrap();
2137                 match err {
2138                         PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
2139                                 match &fails[0] {
2140                                         &APIError::ChannelUnavailable{ref err} =>
2141                                                 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
2142                                         _ => panic!("Unexpected error variant"),
2143                                 }
2144                         },
2145                         _ => panic!("Unexpected error variant"),
2146                 }
2147                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2148                 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put our balance under counterparty-announced channel reserve value".to_string(), 3);
2149         }
2150
2151         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3, recv_value_3);
2152
2153         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1);
2154         let expected_value_to_self = stat01.value_to_self_msat - (recv_value_1 + total_fee_msat) - (recv_value_21 + total_fee_msat) - (recv_value_22 + total_fee_msat) - (recv_value_3 + total_fee_msat);
2155         let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2156         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2157         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2158
2159         let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2160         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2161 }
2162
2163 #[test]
2164 fn channel_reserve_in_flight_removes() {
2165         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2166         // can send to its counterparty, but due to update ordering, the other side may not yet have
2167         // considered those HTLCs fully removed.
2168         // This tests that we don't count HTLCs which will not be included in the next remote
2169         // commitment transaction towards the reserve value (as it implies no commitment transaction
2170         // will be generated which violates the remote reserve value).
2171         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2172         // To test this we:
2173         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2174         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2175         //    you only consider the value of the first HTLC, it may not),
2176         //  * start routing a third HTLC from A to B,
2177         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2178         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2179         //  * deliver the first fulfill from B
2180         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2181         //    claim,
2182         //  * deliver A's response CS and RAA.
2183         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2184         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2185         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2186         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2187         let chanmon_cfgs = create_chanmon_cfgs(2);
2188         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2189         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2190         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2191         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2192         let logger = test_utils::TestLogger::new();
2193
2194         let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2195         // Route the first two HTLCs.
2196         let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
2197         let (payment_preimage_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
2198
2199         // Start routing the third HTLC (this is just used to get everyone in the right state).
2200         let (payment_preimage_3, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
2201         let send_1 = {
2202                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
2203                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
2204                 nodes[0].node.send_payment(&route, payment_hash_3, &None).unwrap();
2205                 check_added_monitors!(nodes[0], 1);
2206                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2207                 assert_eq!(events.len(), 1);
2208                 SendEvent::from_event(events.remove(0))
2209         };
2210
2211         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2212         // initial fulfill/CS.
2213         assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000));
2214         check_added_monitors!(nodes[1], 1);
2215         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2216
2217         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2218         // remove the second HTLC when we send the HTLC back from B to A.
2219         assert!(nodes[1].node.claim_funds(payment_preimage_2, &None, 20000));
2220         check_added_monitors!(nodes[1], 1);
2221         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2222
2223         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2224         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2225         check_added_monitors!(nodes[0], 1);
2226         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2227         expect_payment_sent!(nodes[0], payment_preimage_1);
2228
2229         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2230         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2231         check_added_monitors!(nodes[1], 1);
2232         // B is already AwaitingRAA, so cant generate a CS here
2233         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2234
2235         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2236         check_added_monitors!(nodes[1], 1);
2237         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2238
2239         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2240         check_added_monitors!(nodes[0], 1);
2241         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2242
2243         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2244         check_added_monitors!(nodes[1], 1);
2245         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2246
2247         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2248         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2249         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2250         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2251         // on-chain as necessary).
2252         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2253         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2254         check_added_monitors!(nodes[0], 1);
2255         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2256         expect_payment_sent!(nodes[0], payment_preimage_2);
2257
2258         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2259         check_added_monitors!(nodes[1], 1);
2260         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2261
2262         expect_pending_htlcs_forwardable!(nodes[1]);
2263         expect_payment_received!(nodes[1], payment_hash_3, 100000);
2264
2265         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2266         // resolve the second HTLC from A's point of view.
2267         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2268         check_added_monitors!(nodes[0], 1);
2269         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2270
2271         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2272         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2273         let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[1]);
2274         let send_2 = {
2275                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
2276                 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, &[], 10000, TEST_FINAL_CLTV, &logger).unwrap();
2277                 nodes[1].node.send_payment(&route, payment_hash_4, &None).unwrap();
2278                 check_added_monitors!(nodes[1], 1);
2279                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2280                 assert_eq!(events.len(), 1);
2281                 SendEvent::from_event(events.remove(0))
2282         };
2283
2284         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2285         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2286         check_added_monitors!(nodes[0], 1);
2287         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2288
2289         // Now just resolve all the outstanding messages/HTLCs for completeness...
2290
2291         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2292         check_added_monitors!(nodes[1], 1);
2293         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2294
2295         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2296         check_added_monitors!(nodes[1], 1);
2297
2298         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2299         check_added_monitors!(nodes[0], 1);
2300         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2301
2302         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2303         check_added_monitors!(nodes[1], 1);
2304         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2305
2306         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2307         check_added_monitors!(nodes[0], 1);
2308
2309         expect_pending_htlcs_forwardable!(nodes[0]);
2310         expect_payment_received!(nodes[0], payment_hash_4, 10000);
2311
2312         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4, 10_000);
2313         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3, 100_000);
2314 }
2315
2316 #[test]
2317 fn channel_monitor_network_test() {
2318         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2319         // tests that ChannelMonitor is able to recover from various states.
2320         let chanmon_cfgs = create_chanmon_cfgs(5);
2321         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2322         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2323         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2324
2325         // Create some initial channels
2326         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2327         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2328         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2329         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2330
2331         // Rebalance the network a bit by relaying one payment through all the channels...
2332         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2333         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2334         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2335         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2336
2337         // Simple case with no pending HTLCs:
2338         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2339         check_added_monitors!(nodes[1], 1);
2340         {
2341                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2342                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2343                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
2344                 check_added_monitors!(nodes[0], 1);
2345                 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2346         }
2347         get_announce_close_broadcast_events(&nodes, 0, 1);
2348         assert_eq!(nodes[0].node.list_channels().len(), 0);
2349         assert_eq!(nodes[1].node.list_channels().len(), 1);
2350
2351         // One pending HTLC is discarded by the force-close:
2352         let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2353
2354         // Simple case of one pending HTLC to HTLC-Timeout
2355         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2356         check_added_monitors!(nodes[1], 1);
2357         {
2358                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2359                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2360                 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
2361                 check_added_monitors!(nodes[2], 1);
2362                 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2363         }
2364         get_announce_close_broadcast_events(&nodes, 1, 2);
2365         assert_eq!(nodes[1].node.list_channels().len(), 0);
2366         assert_eq!(nodes[2].node.list_channels().len(), 1);
2367
2368         macro_rules! claim_funds {
2369                 ($node: expr, $prev_node: expr, $preimage: expr, $amount: expr) => {
2370                         {
2371                                 assert!($node.node.claim_funds($preimage, &None, $amount));
2372                                 check_added_monitors!($node, 1);
2373
2374                                 let events = $node.node.get_and_clear_pending_msg_events();
2375                                 assert_eq!(events.len(), 1);
2376                                 match events[0] {
2377                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2378                                                 assert!(update_add_htlcs.is_empty());
2379                                                 assert!(update_fail_htlcs.is_empty());
2380                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2381                                         },
2382                                         _ => panic!("Unexpected event"),
2383                                 };
2384                         }
2385                 }
2386         }
2387
2388         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2389         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2390         nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2391         check_added_monitors!(nodes[2], 1);
2392         let node2_commitment_txid;
2393         {
2394                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2395                 node2_commitment_txid = node_txn[0].txid();
2396
2397                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2398                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, 3_000_000);
2399
2400                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2401                 nodes[3].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
2402                 check_added_monitors!(nodes[3], 1);
2403
2404                 check_preimage_claim(&nodes[3], &node_txn);
2405         }
2406         get_announce_close_broadcast_events(&nodes, 2, 3);
2407         assert_eq!(nodes[2].node.list_channels().len(), 0);
2408         assert_eq!(nodes[3].node.list_channels().len(), 1);
2409
2410         { // Cheat and reset nodes[4]'s height to 1
2411                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2412                 nodes[4].block_notifier.block_connected(&Block { header, txdata: vec![] }, 1);
2413         }
2414
2415         assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
2416         assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
2417         // One pending HTLC to time out:
2418         let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2419         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2420         // buffer space).
2421
2422         let (close_chan_update_1, close_chan_update_2) = {
2423                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2424                 nodes[3].block_notifier.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
2425                 for i in 3..TEST_FINAL_CLTV + 2 + LATENCY_GRACE_PERIOD_BLOCKS + 1 {
2426                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2427                         nodes[3].block_notifier.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
2428                 }
2429                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2430                 assert_eq!(events.len(), 1);
2431                 let close_chan_update_1 = match events[0] {
2432                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2433                                 msg.clone()
2434                         },
2435                         _ => panic!("Unexpected event"),
2436                 };
2437                 check_added_monitors!(nodes[3], 1);
2438
2439                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2440                 {
2441                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2442                         node_txn.retain(|tx| {
2443                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2444                                         false
2445                                 } else { true }
2446                         });
2447                 }
2448
2449                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2450
2451                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2452                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, 3_000_000);
2453
2454                 header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2455
2456                 nodes[4].block_notifier.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
2457                 for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
2458                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2459                         nodes[4].block_notifier.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
2460                 }
2461                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2462                 assert_eq!(events.len(), 1);
2463                 let close_chan_update_2 = match events[0] {
2464                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2465                                 msg.clone()
2466                         },
2467                         _ => panic!("Unexpected event"),
2468                 };
2469                 check_added_monitors!(nodes[4], 1);
2470                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2471
2472                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2473                 nodes[4].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, TEST_FINAL_CLTV - 5);
2474
2475                 check_preimage_claim(&nodes[4], &node_txn);
2476                 (close_chan_update_1, close_chan_update_2)
2477         };
2478         nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2479         nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2480         assert_eq!(nodes[3].node.list_channels().len(), 0);
2481         assert_eq!(nodes[4].node.list_channels().len(), 0);
2482 }
2483
2484 #[test]
2485 fn test_justice_tx() {
2486         // Test justice txn built on revoked HTLC-Success tx, against both sides
2487         let mut alice_config = UserConfig::default();
2488         alice_config.channel_options.announced_channel = true;
2489         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2490         alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2491         let mut bob_config = UserConfig::default();
2492         bob_config.channel_options.announced_channel = true;
2493         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2494         bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2495         let user_cfgs = [Some(alice_config), Some(bob_config)];
2496         let chanmon_cfgs = create_chanmon_cfgs(2);
2497         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2498         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2499         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2500         // Create some new channels:
2501         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2502
2503         // A pending HTLC which will be revoked:
2504         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2505         // Get the will-be-revoked local txn from nodes[0]
2506         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2507         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2508         assert_eq!(revoked_local_txn[0].input.len(), 1);
2509         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2510         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2511         assert_eq!(revoked_local_txn[1].input.len(), 1);
2512         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2513         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2514         // Revoke the old state
2515         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 3_000_000);
2516
2517         {
2518                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2519                 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2520                 {
2521                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2522                         assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2523                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2524
2525                         check_spends!(node_txn[0], revoked_local_txn[0]);
2526                         node_txn.swap_remove(0);
2527                         node_txn.truncate(1);
2528                 }
2529                 check_added_monitors!(nodes[1], 1);
2530                 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2531
2532                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2533                 // Verify broadcast of revoked HTLC-timeout
2534                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2535                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2536                 check_added_monitors!(nodes[0], 1);
2537                 // Broadcast revoked HTLC-timeout on node 1
2538                 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2539                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2540         }
2541         get_announce_close_broadcast_events(&nodes, 0, 1);
2542
2543         assert_eq!(nodes[0].node.list_channels().len(), 0);
2544         assert_eq!(nodes[1].node.list_channels().len(), 0);
2545
2546         // We test justice_tx build by A on B's revoked HTLC-Success tx
2547         // Create some new channels:
2548         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2549         {
2550                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2551                 node_txn.clear();
2552         }
2553
2554         // A pending HTLC which will be revoked:
2555         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2556         // Get the will-be-revoked local txn from B
2557         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2558         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2559         assert_eq!(revoked_local_txn[0].input.len(), 1);
2560         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2561         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2562         // Revoke the old state
2563         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4, 3_000_000);
2564         {
2565                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2566                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2567                 {
2568                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2569                         assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2570                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2571
2572                         check_spends!(node_txn[0], revoked_local_txn[0]);
2573                         node_txn.swap_remove(0);
2574                 }
2575                 check_added_monitors!(nodes[0], 1);
2576                 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2577
2578                 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2579                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2580                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2581                 check_added_monitors!(nodes[1], 1);
2582                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2583                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2584         }
2585         get_announce_close_broadcast_events(&nodes, 0, 1);
2586         assert_eq!(nodes[0].node.list_channels().len(), 0);
2587         assert_eq!(nodes[1].node.list_channels().len(), 0);
2588 }
2589
2590 #[test]
2591 fn revoked_output_claim() {
2592         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2593         // transaction is broadcast by its counterparty
2594         let chanmon_cfgs = create_chanmon_cfgs(2);
2595         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2596         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2597         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2598         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2599         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2600         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2601         assert_eq!(revoked_local_txn.len(), 1);
2602         // Only output is the full channel value back to nodes[0]:
2603         assert_eq!(revoked_local_txn[0].output.len(), 1);
2604         // Send a payment through, updating everyone's latest commitment txn
2605         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000, 5_000_000);
2606
2607         // Inform nodes[1] that nodes[0] broadcast a stale tx
2608         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2609         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2610         check_added_monitors!(nodes[1], 1);
2611         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2612         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2613
2614         check_spends!(node_txn[0], revoked_local_txn[0]);
2615         check_spends!(node_txn[1], chan_1.3);
2616
2617         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2618         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2619         get_announce_close_broadcast_events(&nodes, 0, 1);
2620         check_added_monitors!(nodes[0], 1)
2621 }
2622
2623 #[test]
2624 fn claim_htlc_outputs_shared_tx() {
2625         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2626         let chanmon_cfgs = create_chanmon_cfgs(2);
2627         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2628         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2629         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2630
2631         // Create some new channel:
2632         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2633
2634         // Rebalance the network to generate htlc in the two directions
2635         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2636         // node[0] is gonna to revoke an old state thus node[1] should be able to claim both offered/received HTLC outputs on top of commitment tx
2637         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2638         let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2639
2640         // Get the will-be-revoked local txn from node[0]
2641         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2642         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2643         assert_eq!(revoked_local_txn[0].input.len(), 1);
2644         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2645         assert_eq!(revoked_local_txn[1].input.len(), 1);
2646         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2647         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2648         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2649
2650         //Revoke the old state
2651         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2652
2653         {
2654                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2655                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2656                 check_added_monitors!(nodes[0], 1);
2657                 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2658                 check_added_monitors!(nodes[1], 1);
2659                 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
2660                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2661
2662                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2663                 assert_eq!(node_txn.len(), 3); // ChannelMonitor: penalty tx, ChannelManager: local commitment + HTLC-timeout
2664
2665                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2666                 check_spends!(node_txn[0], revoked_local_txn[0]);
2667
2668                 let mut witness_lens = BTreeSet::new();
2669                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2670                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2671                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2672                 assert_eq!(witness_lens.len(), 3);
2673                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2674                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2675                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2676
2677                 // Next nodes[1] broadcasts its current local tx state:
2678                 assert_eq!(node_txn[1].input.len(), 1);
2679                 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2680
2681                 assert_eq!(node_txn[2].input.len(), 1);
2682                 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
2683                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2684                 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
2685                 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
2686                 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
2687         }
2688         get_announce_close_broadcast_events(&nodes, 0, 1);
2689         assert_eq!(nodes[0].node.list_channels().len(), 0);
2690         assert_eq!(nodes[1].node.list_channels().len(), 0);
2691 }
2692
2693 #[test]
2694 fn claim_htlc_outputs_single_tx() {
2695         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2696         let chanmon_cfgs = create_chanmon_cfgs(2);
2697         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2698         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2699         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2700
2701         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2702
2703         // Rebalance the network to generate htlc in the two directions
2704         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2705         // node[0] is gonna to revoke an old state thus node[1] should be able to claim both offered/received HTLC outputs on top of commitment tx, but this
2706         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2707         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2708         let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2709
2710         // Get the will-be-revoked local txn from node[0]
2711         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2712
2713         //Revoke the old state
2714         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2715
2716         {
2717                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2718                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2719                 check_added_monitors!(nodes[0], 1);
2720                 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2721                 check_added_monitors!(nodes[1], 1);
2722                 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
2723
2724                 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 200, true, header.block_hash());
2725                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2726
2727                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2728                 assert_eq!(node_txn.len(), 9);
2729                 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2730                 // ChannelManager: local commmitment + local HTLC-timeout (2)
2731                 // ChannelMonitor: bumped justice tx, after one increase, bumps on HTLC aren't generated not being substantial anymore, bump on revoked to_local isn't generated due to more room for expiration (2)
2732                 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2733
2734                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2735                 assert_eq!(node_txn[2].input.len(), 1);
2736                 check_spends!(node_txn[2], chan_1.3);
2737                 assert_eq!(node_txn[3].input.len(), 1);
2738                 let witness_script = node_txn[3].input[0].witness.last().unwrap();
2739                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2740                 check_spends!(node_txn[3], node_txn[2]);
2741
2742                 // Justice transactions are indices 1-2-4
2743                 assert_eq!(node_txn[0].input.len(), 1);
2744                 assert_eq!(node_txn[1].input.len(), 1);
2745                 assert_eq!(node_txn[4].input.len(), 1);
2746
2747                 check_spends!(node_txn[0], revoked_local_txn[0]);
2748                 check_spends!(node_txn[1], revoked_local_txn[0]);
2749                 check_spends!(node_txn[4], revoked_local_txn[0]);
2750
2751                 let mut witness_lens = BTreeSet::new();
2752                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2753                 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2754                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2755                 assert_eq!(witness_lens.len(), 3);
2756                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2757                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2758                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2759         }
2760         get_announce_close_broadcast_events(&nodes, 0, 1);
2761         assert_eq!(nodes[0].node.list_channels().len(), 0);
2762         assert_eq!(nodes[1].node.list_channels().len(), 0);
2763 }
2764
2765 #[test]
2766 fn test_htlc_on_chain_success() {
2767         // Test that in case of a unilateral close onchain, we detect the state of output thanks to
2768         // ChainWatchInterface and pass the preimage backward accordingly. So here we test that ChannelManager is
2769         // broadcasting the right event to other nodes in payment path.
2770         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2771         // A --------------------> B ----------------------> C (preimage)
2772         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2773         // commitment transaction was broadcast.
2774         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2775         // towards B.
2776         // B should be able to claim via preimage if A then broadcasts its local tx.
2777         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2778         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2779         // PaymentSent event).
2780
2781         let chanmon_cfgs = create_chanmon_cfgs(3);
2782         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2783         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2784         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2785
2786         // Create some initial channels
2787         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2788         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2789
2790         // Rebalance the network a bit by relaying one payment through all the channels...
2791         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2792         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2793
2794         let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2795         let (our_payment_preimage_2, _payment_hash_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2796         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2797
2798         // Broadcast legit commitment tx from C on B's chain
2799         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2800         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2801         assert_eq!(commitment_tx.len(), 1);
2802         check_spends!(commitment_tx[0], chan_2.3);
2803         nodes[2].node.claim_funds(our_payment_preimage, &None, 3_000_000);
2804         nodes[2].node.claim_funds(our_payment_preimage_2, &None, 3_000_000);
2805         check_added_monitors!(nodes[2], 2);
2806         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2807         assert!(updates.update_add_htlcs.is_empty());
2808         assert!(updates.update_fail_htlcs.is_empty());
2809         assert!(updates.update_fail_malformed_htlcs.is_empty());
2810         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2811
2812         nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2813         check_closed_broadcast!(nodes[2], false);
2814         check_added_monitors!(nodes[2], 1);
2815         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx, 2*htlc-success tx), ChannelMonitor : 2 (2 * HTLC-Success tx)
2816         assert_eq!(node_txn.len(), 5);
2817         assert_eq!(node_txn[0], node_txn[3]);
2818         assert_eq!(node_txn[1], node_txn[4]);
2819         assert_eq!(node_txn[2], commitment_tx[0]);
2820         check_spends!(node_txn[0], commitment_tx[0]);
2821         check_spends!(node_txn[1], commitment_tx[0]);
2822         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2823         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2824         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2825         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2826         assert_eq!(node_txn[0].lock_time, 0);
2827         assert_eq!(node_txn[1].lock_time, 0);
2828
2829         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2830         nodes[1].block_notifier.block_connected(&Block { header, txdata: node_txn}, 1);
2831         {
2832                 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
2833                 assert_eq!(added_monitors.len(), 1);
2834                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2835                 added_monitors.clear();
2836         }
2837         let events = nodes[1].node.get_and_clear_pending_msg_events();
2838         {
2839                 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
2840                 assert_eq!(added_monitors.len(), 2);
2841                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2842                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2843                 added_monitors.clear();
2844         }
2845         assert_eq!(events.len(), 2);
2846         match events[0] {
2847                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2848                 _ => panic!("Unexpected event"),
2849         }
2850         match events[1] {
2851                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
2852                         assert!(update_add_htlcs.is_empty());
2853                         assert!(update_fail_htlcs.is_empty());
2854                         assert_eq!(update_fulfill_htlcs.len(), 1);
2855                         assert!(update_fail_malformed_htlcs.is_empty());
2856                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2857                 },
2858                 _ => panic!("Unexpected event"),
2859         };
2860         macro_rules! check_tx_local_broadcast {
2861                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2862                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2863                         assert_eq!(node_txn.len(), 5);
2864                         // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2865                         // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2866                         check_spends!(node_txn[0], $commitment_tx);
2867                         check_spends!(node_txn[1], $commitment_tx);
2868                         assert_ne!(node_txn[0].lock_time, 0);
2869                         assert_ne!(node_txn[1].lock_time, 0);
2870                         if $htlc_offered {
2871                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2872                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2873                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2874                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2875                         } else {
2876                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2877                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2878                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2879                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2880                         }
2881                         check_spends!(node_txn[2], $chan_tx);
2882                         check_spends!(node_txn[3], node_txn[2]);
2883                         check_spends!(node_txn[4], node_txn[2]);
2884                         assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), 71);
2885                         assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2886                         assert_eq!(node_txn[4].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2887                         assert!(node_txn[3].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2888                         assert!(node_txn[4].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2889                         assert_ne!(node_txn[3].lock_time, 0);
2890                         assert_ne!(node_txn[4].lock_time, 0);
2891                         node_txn.clear();
2892                 } }
2893         }
2894         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2895         // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2896         // timeout-claim of the output that nodes[2] just claimed via success.
2897         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2898
2899         // Broadcast legit commitment tx from A on B's chain
2900         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2901         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2902         check_spends!(commitment_tx[0], chan_1.3);
2903         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2904         check_closed_broadcast!(nodes[1], false);
2905         check_added_monitors!(nodes[1], 1);
2906         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 1 (HTLC-Success)
2907         assert_eq!(node_txn.len(), 4);
2908         check_spends!(node_txn[0], commitment_tx[0]);
2909         assert_eq!(node_txn[0].input.len(), 2);
2910         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2911         assert_eq!(node_txn[0].input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2912         assert_eq!(node_txn[0].lock_time, 0);
2913         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2914         check_spends!(node_txn[1], chan_1.3);
2915         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
2916         check_spends!(node_txn[2], node_txn[1]);
2917         check_spends!(node_txn[3], node_txn[1]);
2918         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2919         // we already checked the same situation with A.
2920
2921         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2922         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
2923         check_closed_broadcast!(nodes[0], false);
2924         check_added_monitors!(nodes[0], 1);
2925         let events = nodes[0].node.get_and_clear_pending_events();
2926         assert_eq!(events.len(), 2);
2927         let mut first_claimed = false;
2928         for event in events {
2929                 match event {
2930                         Event::PaymentSent { payment_preimage } => {
2931                                 if payment_preimage == our_payment_preimage {
2932                                         assert!(!first_claimed);
2933                                         first_claimed = true;
2934                                 } else {
2935                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2936                                 }
2937                         },
2938                         _ => panic!("Unexpected event"),
2939                 }
2940         }
2941         check_tx_local_broadcast!(nodes[0], true, commitment_tx[0], chan_1.3);
2942 }
2943
2944 #[test]
2945 fn test_htlc_on_chain_timeout() {
2946         // Test that in case of a unilateral close onchain, we detect the state of output thanks to
2947         // ChainWatchInterface and timeout the HTLC backward accordingly. So here we test that ChannelManager is
2948         // broadcasting the right event to other nodes in payment path.
2949         // A ------------------> B ----------------------> C (timeout)
2950         //    B's commitment tx                 C's commitment tx
2951         //            \                                  \
2952         //         B's HTLC timeout tx               B's timeout tx
2953
2954         let chanmon_cfgs = create_chanmon_cfgs(3);
2955         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2956         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2957         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2958
2959         // Create some intial channels
2960         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2961         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2962
2963         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2964         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2965         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2966
2967         let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2968         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2969
2970         // Broadcast legit commitment tx from C on B's chain
2971         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2972         check_spends!(commitment_tx[0], chan_2.3);
2973         nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
2974         check_added_monitors!(nodes[2], 0);
2975         expect_pending_htlcs_forwardable!(nodes[2]);
2976         check_added_monitors!(nodes[2], 1);
2977
2978         let events = nodes[2].node.get_and_clear_pending_msg_events();
2979         assert_eq!(events.len(), 1);
2980         match events[0] {
2981                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
2982                         assert!(update_add_htlcs.is_empty());
2983                         assert!(!update_fail_htlcs.is_empty());
2984                         assert!(update_fulfill_htlcs.is_empty());
2985                         assert!(update_fail_malformed_htlcs.is_empty());
2986                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2987                 },
2988                 _ => panic!("Unexpected event"),
2989         };
2990         nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2991         check_closed_broadcast!(nodes[2], false);
2992         check_added_monitors!(nodes[2], 1);
2993         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2994         assert_eq!(node_txn.len(), 1);
2995         check_spends!(node_txn[0], chan_2.3);
2996         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2997
2998         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2999         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
3000         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
3001         let timeout_tx;
3002         {
3003                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3004                 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
3005                 assert_eq!(node_txn[1], node_txn[3]);
3006                 assert_eq!(node_txn[2], node_txn[4]);
3007
3008                 check_spends!(node_txn[0], commitment_tx[0]);
3009                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3010
3011                 check_spends!(node_txn[1], chan_2.3);
3012                 check_spends!(node_txn[2], node_txn[1]);
3013                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
3014                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3015
3016                 timeout_tx = node_txn[0].clone();
3017                 node_txn.clear();
3018         }
3019
3020         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![timeout_tx]}, 1);
3021         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
3022         check_added_monitors!(nodes[1], 1);
3023         check_closed_broadcast!(nodes[1], false);
3024
3025         expect_pending_htlcs_forwardable!(nodes[1]);
3026         check_added_monitors!(nodes[1], 1);
3027         let events = nodes[1].node.get_and_clear_pending_msg_events();
3028         assert_eq!(events.len(), 1);
3029         match events[0] {
3030                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
3031                         assert!(update_add_htlcs.is_empty());
3032                         assert!(!update_fail_htlcs.is_empty());
3033                         assert!(update_fulfill_htlcs.is_empty());
3034                         assert!(update_fail_malformed_htlcs.is_empty());
3035                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3036                 },
3037                 _ => panic!("Unexpected event"),
3038         };
3039         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // Well... here we detect our own htlc_timeout_tx so no tx to be generated
3040         assert_eq!(node_txn.len(), 0);
3041
3042         // Broadcast legit commitment tx from B on A's chain
3043         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3044         check_spends!(commitment_tx[0], chan_1.3);
3045
3046         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
3047         check_closed_broadcast!(nodes[0], false);
3048         check_added_monitors!(nodes[0], 1);
3049         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 1 timeout tx
3050         assert_eq!(node_txn.len(), 3);
3051         check_spends!(node_txn[0], commitment_tx[0]);
3052         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3053         check_spends!(node_txn[1], chan_1.3);
3054         check_spends!(node_txn[2], node_txn[1]);
3055         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
3056         assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3057 }
3058
3059 #[test]
3060 fn test_simple_commitment_revoked_fail_backward() {
3061         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3062         // and fail backward accordingly.
3063
3064         let chanmon_cfgs = create_chanmon_cfgs(3);
3065         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3066         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3067         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3068
3069         // Create some initial channels
3070         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3071         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3072
3073         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3074         // Get the will-be-revoked local txn from nodes[2]
3075         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3076         // Revoke the old state
3077         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, 3_000_000);
3078
3079         let (_, payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3080
3081         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
3082         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3083         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
3084         check_added_monitors!(nodes[1], 1);
3085         check_closed_broadcast!(nodes[1], false);
3086
3087         expect_pending_htlcs_forwardable!(nodes[1]);
3088         check_added_monitors!(nodes[1], 1);
3089         let events = nodes[1].node.get_and_clear_pending_msg_events();
3090         assert_eq!(events.len(), 1);
3091         match events[0] {
3092                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, ref commitment_signed, .. } } => {
3093                         assert!(update_add_htlcs.is_empty());
3094                         assert_eq!(update_fail_htlcs.len(), 1);
3095                         assert!(update_fulfill_htlcs.is_empty());
3096                         assert!(update_fail_malformed_htlcs.is_empty());
3097                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3098
3099                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3100                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3101
3102                         let events = nodes[0].node.get_and_clear_pending_msg_events();
3103                         assert_eq!(events.len(), 1);
3104                         match events[0] {
3105                                 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3106                                 _ => panic!("Unexpected event"),
3107                         }
3108                         expect_payment_failed!(nodes[0], payment_hash, false);
3109                 },
3110                 _ => panic!("Unexpected event"),
3111         }
3112 }
3113
3114 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3115         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3116         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3117         // commitment transaction anymore.
3118         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3119         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3120         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3121         // technically disallowed and we should probably handle it reasonably.
3122         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3123         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3124         // transactions:
3125         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3126         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3127         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3128         //   and once they revoke the previous commitment transaction (allowing us to send a new
3129         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3130         let chanmon_cfgs = create_chanmon_cfgs(3);
3131         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3132         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3133         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3134
3135         // Create some initial channels
3136         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3137         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3138
3139         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3140         // Get the will-be-revoked local txn from nodes[2]
3141         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3142         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3143         // Revoke the old state
3144         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, if no_to_remote { 10_000 } else { 3_000_000});
3145
3146         let value = if use_dust {
3147                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3148                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3149                 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3150         } else { 3000000 };
3151
3152         let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3153         let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3154         let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3155
3156         assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, &None));
3157         expect_pending_htlcs_forwardable!(nodes[2]);
3158         check_added_monitors!(nodes[2], 1);
3159         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3160         assert!(updates.update_add_htlcs.is_empty());
3161         assert!(updates.update_fulfill_htlcs.is_empty());
3162         assert!(updates.update_fail_malformed_htlcs.is_empty());
3163         assert_eq!(updates.update_fail_htlcs.len(), 1);
3164         assert!(updates.update_fee.is_none());
3165         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3166         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3167         // Drop the last RAA from 3 -> 2
3168
3169         assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, &None));
3170         expect_pending_htlcs_forwardable!(nodes[2]);
3171         check_added_monitors!(nodes[2], 1);
3172         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3173         assert!(updates.update_add_htlcs.is_empty());
3174         assert!(updates.update_fulfill_htlcs.is_empty());
3175         assert!(updates.update_fail_malformed_htlcs.is_empty());
3176         assert_eq!(updates.update_fail_htlcs.len(), 1);
3177         assert!(updates.update_fee.is_none());
3178         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3179         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3180         check_added_monitors!(nodes[1], 1);
3181         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3182         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3183         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3184         check_added_monitors!(nodes[2], 1);
3185
3186         assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, &None));
3187         expect_pending_htlcs_forwardable!(nodes[2]);
3188         check_added_monitors!(nodes[2], 1);
3189         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3190         assert!(updates.update_add_htlcs.is_empty());
3191         assert!(updates.update_fulfill_htlcs.is_empty());
3192         assert!(updates.update_fail_malformed_htlcs.is_empty());
3193         assert_eq!(updates.update_fail_htlcs.len(), 1);
3194         assert!(updates.update_fee.is_none());
3195         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3196         // At this point first_payment_hash has dropped out of the latest two commitment
3197         // transactions that nodes[1] is tracking...
3198         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3199         check_added_monitors!(nodes[1], 1);
3200         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3201         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3202         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3203         check_added_monitors!(nodes[2], 1);
3204
3205         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3206         // on nodes[2]'s RAA.
3207         let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3208         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3209         let logger = test_utils::TestLogger::new();
3210         let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3211         nodes[1].node.send_payment(&route, fourth_payment_hash, &None).unwrap();
3212         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3213         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3214         check_added_monitors!(nodes[1], 0);
3215
3216         if deliver_bs_raa {
3217                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3218                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3219                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3220                 check_added_monitors!(nodes[1], 1);
3221                 let events = nodes[1].node.get_and_clear_pending_events();
3222                 assert_eq!(events.len(), 1);
3223                 match events[0] {
3224                         Event::PendingHTLCsForwardable { .. } => { },
3225                         _ => panic!("Unexpected event"),
3226                 };
3227                 // Deliberately don't process the pending fail-back so they all fail back at once after
3228                 // block connection just like the !deliver_bs_raa case
3229         }
3230
3231         let mut failed_htlcs = HashSet::new();
3232         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3233
3234         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
3235         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3236         check_added_monitors!(nodes[1], 1);
3237         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
3238
3239         let events = nodes[1].node.get_and_clear_pending_events();
3240         assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
3241         match events[0] {
3242                 Event::PaymentFailed { ref payment_hash, .. } => {
3243                         assert_eq!(*payment_hash, fourth_payment_hash);
3244                 },
3245                 _ => panic!("Unexpected event"),
3246         }
3247         if !deliver_bs_raa {
3248                 match events[1] {
3249                         Event::PendingHTLCsForwardable { .. } => { },
3250                         _ => panic!("Unexpected event"),
3251                 };
3252         }
3253         nodes[1].node.process_pending_htlc_forwards();
3254         check_added_monitors!(nodes[1], 1);
3255
3256         let events = nodes[1].node.get_and_clear_pending_msg_events();
3257         assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
3258         match events[if deliver_bs_raa { 1 } else { 0 }] {
3259                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3260                 _ => panic!("Unexpected event"),
3261         }
3262         if deliver_bs_raa {
3263                 match events[0] {
3264                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
3265                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3266                                 assert_eq!(update_add_htlcs.len(), 1);
3267                                 assert!(update_fulfill_htlcs.is_empty());
3268                                 assert!(update_fail_htlcs.is_empty());
3269                                 assert!(update_fail_malformed_htlcs.is_empty());
3270                         },
3271                         _ => panic!("Unexpected event"),
3272                 }
3273         }
3274         match events[if deliver_bs_raa { 2 } else { 1 }] {
3275                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, ref commitment_signed, .. } } => {
3276                         assert!(update_add_htlcs.is_empty());
3277                         assert_eq!(update_fail_htlcs.len(), 3);
3278                         assert!(update_fulfill_htlcs.is_empty());
3279                         assert!(update_fail_malformed_htlcs.is_empty());
3280                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3281
3282                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3283                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3284                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3285
3286                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3287
3288                         let events = nodes[0].node.get_and_clear_pending_msg_events();
3289                         // If we delivered B's RAA we got an unknown preimage error, not something
3290                         // that we should update our routing table for.
3291                         assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
3292                         for event in events {
3293                                 match event {
3294                                         MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3295                                         _ => panic!("Unexpected event"),
3296                                 }
3297                         }
3298                         let events = nodes[0].node.get_and_clear_pending_events();
3299                         assert_eq!(events.len(), 3);
3300                         match events[0] {
3301                                 Event::PaymentFailed { ref payment_hash, .. } => {
3302                                         assert!(failed_htlcs.insert(payment_hash.0));
3303                                 },
3304                                 _ => panic!("Unexpected event"),
3305                         }
3306                         match events[1] {
3307                                 Event::PaymentFailed { ref payment_hash, .. } => {
3308                                         assert!(failed_htlcs.insert(payment_hash.0));
3309                                 },
3310                                 _ => panic!("Unexpected event"),
3311                         }
3312                         match events[2] {
3313                                 Event::PaymentFailed { ref payment_hash, .. } => {
3314                                         assert!(failed_htlcs.insert(payment_hash.0));
3315                                 },
3316                                 _ => panic!("Unexpected event"),
3317                         }
3318                 },
3319                 _ => panic!("Unexpected event"),
3320         }
3321
3322         assert!(failed_htlcs.contains(&first_payment_hash.0));
3323         assert!(failed_htlcs.contains(&second_payment_hash.0));
3324         assert!(failed_htlcs.contains(&third_payment_hash.0));
3325 }
3326
3327 #[test]
3328 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3329         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3330         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3331         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3332         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3333 }
3334
3335 #[test]
3336 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3337         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3338         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3339         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3340         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3341 }
3342
3343 #[test]
3344 fn fail_backward_pending_htlc_upon_channel_failure() {
3345         let chanmon_cfgs = create_chanmon_cfgs(2);
3346         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3347         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3348         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3349         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3350         let logger = test_utils::TestLogger::new();
3351
3352         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3353         {
3354                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
3355                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3356                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3357                 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
3358                 check_added_monitors!(nodes[0], 1);
3359
3360                 let payment_event = {
3361                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3362                         assert_eq!(events.len(), 1);
3363                         SendEvent::from_event(events.remove(0))
3364                 };
3365                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3366                 assert_eq!(payment_event.msgs.len(), 1);
3367         }
3368
3369         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3370         let (_, failed_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3371         {
3372                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3373                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3374                 nodes[0].node.send_payment(&route, failed_payment_hash, &None).unwrap();
3375                 check_added_monitors!(nodes[0], 0);
3376
3377                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3378         }
3379
3380         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3381         {
3382                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[1]);
3383
3384                 let secp_ctx = Secp256k1::new();
3385                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3386                 let current_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
3387                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3388                 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3389                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &None, current_height).unwrap();
3390                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3391                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3392
3393                 // Send a 0-msat update_add_htlc to fail the channel.
3394                 let update_add_htlc = msgs::UpdateAddHTLC {
3395                         channel_id: chan.2,
3396                         htlc_id: 0,
3397                         amount_msat: 0,
3398                         payment_hash,
3399                         cltv_expiry,
3400                         onion_routing_packet,
3401                 };
3402                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3403         }
3404
3405         // Check that Alice fails backward the pending HTLC from the second payment.
3406         expect_payment_failed!(nodes[0], failed_payment_hash, true);
3407         check_closed_broadcast!(nodes[0], true);
3408         check_added_monitors!(nodes[0], 1);
3409 }
3410
3411 #[test]
3412 fn test_htlc_ignore_latest_remote_commitment() {
3413         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3414         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3415         let chanmon_cfgs = create_chanmon_cfgs(2);
3416         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3417         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3418         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3419         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3420
3421         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3422         nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
3423         check_closed_broadcast!(nodes[0], false);
3424         check_added_monitors!(nodes[0], 1);
3425
3426         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3427         assert_eq!(node_txn.len(), 2);
3428
3429         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3430         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3431         check_closed_broadcast!(nodes[1], false);
3432         check_added_monitors!(nodes[1], 1);
3433
3434         // Duplicate the block_connected call since this may happen due to other listeners
3435         // registering new transactions
3436         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3437 }
3438
3439 #[test]
3440 fn test_force_close_fail_back() {
3441         // Check which HTLCs are failed-backwards on channel force-closure
3442         let chanmon_cfgs = create_chanmon_cfgs(3);
3443         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3444         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3445         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3446         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3447         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3448         let logger = test_utils::TestLogger::new();
3449
3450         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3451
3452         let mut payment_event = {
3453                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3454                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, 42, &logger).unwrap();
3455                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
3456                 check_added_monitors!(nodes[0], 1);
3457
3458                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3459                 assert_eq!(events.len(), 1);
3460                 SendEvent::from_event(events.remove(0))
3461         };
3462
3463         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3464         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3465
3466         expect_pending_htlcs_forwardable!(nodes[1]);
3467
3468         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3469         assert_eq!(events_2.len(), 1);
3470         payment_event = SendEvent::from_event(events_2.remove(0));
3471         assert_eq!(payment_event.msgs.len(), 1);
3472
3473         check_added_monitors!(nodes[1], 1);
3474         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3475         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3476         check_added_monitors!(nodes[2], 1);
3477         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3478
3479         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3480         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3481         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3482
3483         nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
3484         check_closed_broadcast!(nodes[2], false);
3485         check_added_monitors!(nodes[2], 1);
3486         let tx = {
3487                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3488                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3489                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3490                 // back to nodes[1] upon timeout otherwise.
3491                 assert_eq!(node_txn.len(), 1);
3492                 node_txn.remove(0)
3493         };
3494
3495         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3496         nodes[1].block_notifier.block_connected_checked(&header, 1, &[&tx], &[1]);
3497
3498         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3499         check_closed_broadcast!(nodes[1], false);
3500         check_added_monitors!(nodes[1], 1);
3501
3502         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3503         {
3504                 let mut monitors = nodes[2].chan_monitor.simple_monitor.monitors.lock().unwrap();
3505                 monitors.get_mut(&OutPoint{ txid: Txid::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), index: 0 }).unwrap()
3506                         .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
3507         }
3508         nodes[2].block_notifier.block_connected_checked(&header, 1, &[&tx], &[1]);
3509         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3510         assert_eq!(node_txn.len(), 1);
3511         assert_eq!(node_txn[0].input.len(), 1);
3512         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3513         assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3514         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3515
3516         check_spends!(node_txn[0], tx);
3517 }
3518
3519 #[test]
3520 fn test_unconf_chan() {
3521         // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
3522         let chanmon_cfgs = create_chanmon_cfgs(2);
3523         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3524         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3525         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3526         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3527
3528         let channel_state = nodes[0].node.channel_state.lock().unwrap();
3529         assert_eq!(channel_state.by_id.len(), 1);
3530         assert_eq!(channel_state.short_to_id.len(), 1);
3531         mem::drop(channel_state);
3532
3533         let mut headers = Vec::new();
3534         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3535         headers.push(header.clone());
3536         for _i in 2..100 {
3537                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3538                 headers.push(header.clone());
3539         }
3540         let mut height = 99;
3541         while !headers.is_empty() {
3542                 nodes[0].node.block_disconnected(&headers.pop().unwrap(), height);
3543                 height -= 1;
3544         }
3545         check_closed_broadcast!(nodes[0], false);
3546         check_added_monitors!(nodes[0], 1);
3547         let channel_state = nodes[0].node.channel_state.lock().unwrap();
3548         assert_eq!(channel_state.by_id.len(), 0);
3549         assert_eq!(channel_state.short_to_id.len(), 0);
3550 }
3551
3552 #[test]
3553 fn test_simple_peer_disconnect() {
3554         // Test that we can reconnect when there are no lost messages
3555         let chanmon_cfgs = create_chanmon_cfgs(3);
3556         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3557         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3558         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3559         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3560         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3561
3562         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3563         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3564         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3565
3566         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3567         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3568         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3569         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1, 1_000_000);
3570
3571         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3572         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3573         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3574
3575         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3576         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3577         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3578         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3579
3580         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3581         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3582
3583         claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3, 1_000_000);
3584         fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
3585
3586         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3587         {
3588                 let events = nodes[0].node.get_and_clear_pending_events();
3589                 assert_eq!(events.len(), 2);
3590                 match events[0] {
3591                         Event::PaymentSent { payment_preimage } => {
3592                                 assert_eq!(payment_preimage, payment_preimage_3);
3593                         },
3594                         _ => panic!("Unexpected event"),
3595                 }
3596                 match events[1] {
3597                         Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
3598                                 assert_eq!(payment_hash, payment_hash_5);
3599                                 assert!(rejected_by_dest);
3600                         },
3601                         _ => panic!("Unexpected event"),
3602                 }
3603         }
3604
3605         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4, 1_000_000);
3606         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3607 }
3608
3609 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
3610         // Test that we can reconnect when in-flight HTLC updates get dropped
3611         let chanmon_cfgs = create_chanmon_cfgs(2);
3612         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3613         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3614         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3615         if messages_delivered == 0 {
3616                 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3617                 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3618         } else {
3619                 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3620         }
3621
3622         let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
3623
3624         let logger = test_utils::TestLogger::new();
3625         let payment_event = {
3626                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3627                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3628                         &nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3629                         &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3630                 nodes[0].node.send_payment(&route, payment_hash_1, &None).unwrap();
3631                 check_added_monitors!(nodes[0], 1);
3632
3633                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3634                 assert_eq!(events.len(), 1);
3635                 SendEvent::from_event(events.remove(0))
3636         };
3637         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3638
3639         if messages_delivered < 2 {
3640                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3641         } else {
3642                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3643                 if messages_delivered >= 3 {
3644                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3645                         check_added_monitors!(nodes[1], 1);
3646                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3647
3648                         if messages_delivered >= 4 {
3649                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3650                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3651                                 check_added_monitors!(nodes[0], 1);
3652
3653                                 if messages_delivered >= 5 {
3654                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3655                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3656                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3657                                         check_added_monitors!(nodes[0], 1);
3658
3659                                         if messages_delivered >= 6 {
3660                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3661                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3662                                                 check_added_monitors!(nodes[1], 1);
3663                                         }
3664                                 }
3665                         }
3666                 }
3667         }
3668
3669         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3670         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3671         if messages_delivered < 3 {
3672                 // Even if the funding_locked messages get exchanged, as long as nothing further was
3673                 // received on either side, both sides will need to resend them.
3674                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
3675         } else if messages_delivered == 3 {
3676                 // nodes[0] still wants its RAA + commitment_signed
3677                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
3678         } else if messages_delivered == 4 {
3679                 // nodes[0] still wants its commitment_signed
3680                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3681         } else if messages_delivered == 5 {
3682                 // nodes[1] still wants its final RAA
3683                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3684         } else if messages_delivered == 6 {
3685                 // Everything was delivered...
3686                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3687         }
3688
3689         let events_1 = nodes[1].node.get_and_clear_pending_events();
3690         assert_eq!(events_1.len(), 1);
3691         match events_1[0] {
3692                 Event::PendingHTLCsForwardable { .. } => { },
3693                 _ => panic!("Unexpected event"),
3694         };
3695
3696         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3697         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3698         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3699
3700         nodes[1].node.process_pending_htlc_forwards();
3701
3702         let events_2 = nodes[1].node.get_and_clear_pending_events();
3703         assert_eq!(events_2.len(), 1);
3704         match events_2[0] {
3705                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
3706                         assert_eq!(payment_hash_1, *payment_hash);
3707                         assert_eq!(*payment_secret, None);
3708                         assert_eq!(amt, 1000000);
3709                 },
3710                 _ => panic!("Unexpected event"),
3711         }
3712
3713         nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000);
3714         check_added_monitors!(nodes[1], 1);
3715
3716         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3717         assert_eq!(events_3.len(), 1);
3718         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3719                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3720                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3721                         assert!(updates.update_add_htlcs.is_empty());
3722                         assert!(updates.update_fail_htlcs.is_empty());
3723                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3724                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3725                         assert!(updates.update_fee.is_none());
3726                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3727                 },
3728                 _ => panic!("Unexpected event"),
3729         };
3730
3731         if messages_delivered >= 1 {
3732                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3733
3734                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3735                 assert_eq!(events_4.len(), 1);
3736                 match events_4[0] {
3737                         Event::PaymentSent { ref payment_preimage } => {
3738                                 assert_eq!(payment_preimage_1, *payment_preimage);
3739                         },
3740                         _ => panic!("Unexpected event"),
3741                 }
3742
3743                 if messages_delivered >= 2 {
3744                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3745                         check_added_monitors!(nodes[0], 1);
3746                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3747
3748                         if messages_delivered >= 3 {
3749                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3750                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3751                                 check_added_monitors!(nodes[1], 1);
3752
3753                                 if messages_delivered >= 4 {
3754                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3755                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3756                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3757                                         check_added_monitors!(nodes[1], 1);
3758
3759                                         if messages_delivered >= 5 {
3760                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3761                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3762                                                 check_added_monitors!(nodes[0], 1);
3763                                         }
3764                                 }
3765                         }
3766                 }
3767         }
3768
3769         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3770         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3771         if messages_delivered < 2 {
3772                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
3773                 //TODO: Deduplicate PaymentSent events, then enable this if:
3774                 //if messages_delivered < 1 {
3775                         let events_4 = nodes[0].node.get_and_clear_pending_events();
3776                         assert_eq!(events_4.len(), 1);
3777                         match events_4[0] {
3778                                 Event::PaymentSent { ref payment_preimage } => {
3779                                         assert_eq!(payment_preimage_1, *payment_preimage);
3780                                 },
3781                                 _ => panic!("Unexpected event"),
3782                         }
3783                 //}
3784         } else if messages_delivered == 2 {
3785                 // nodes[0] still wants its RAA + commitment_signed
3786                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
3787         } else if messages_delivered == 3 {
3788                 // nodes[0] still wants its commitment_signed
3789                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
3790         } else if messages_delivered == 4 {
3791                 // nodes[1] still wants its final RAA
3792                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3793         } else if messages_delivered == 5 {
3794                 // Everything was delivered...
3795                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3796         }
3797
3798         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3799         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3800         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3801
3802         // Channel should still work fine...
3803         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3804         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3805                 &nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3806                 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3807         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3808         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3809 }
3810
3811 #[test]
3812 fn test_drop_messages_peer_disconnect_a() {
3813         do_test_drop_messages_peer_disconnect(0);
3814         do_test_drop_messages_peer_disconnect(1);
3815         do_test_drop_messages_peer_disconnect(2);
3816         do_test_drop_messages_peer_disconnect(3);
3817 }
3818
3819 #[test]
3820 fn test_drop_messages_peer_disconnect_b() {
3821         do_test_drop_messages_peer_disconnect(4);
3822         do_test_drop_messages_peer_disconnect(5);
3823         do_test_drop_messages_peer_disconnect(6);
3824 }
3825
3826 #[test]
3827 fn test_funding_peer_disconnect() {
3828         // Test that we can lock in our funding tx while disconnected
3829         let chanmon_cfgs = create_chanmon_cfgs(2);
3830         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3831         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3832         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3833         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3834
3835         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3836         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3837
3838         confirm_transaction(&nodes[0].block_notifier, &nodes[0].chain_monitor, &tx, tx.version);
3839         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3840         assert_eq!(events_1.len(), 1);
3841         match events_1[0] {
3842                 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3843                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3844                 },
3845                 _ => panic!("Unexpected event"),
3846         }
3847
3848         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3849
3850         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3851         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3852
3853         confirm_transaction(&nodes[1].block_notifier, &nodes[1].chain_monitor, &tx, tx.version);
3854         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3855         assert_eq!(events_2.len(), 2);
3856         let funding_locked = match events_2[0] {
3857                 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3858                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3859                         msg.clone()
3860                 },
3861                 _ => panic!("Unexpected event"),
3862         };
3863         let bs_announcement_sigs = match events_2[1] {
3864                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3865                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3866                         msg.clone()
3867                 },
3868                 _ => panic!("Unexpected event"),
3869         };
3870
3871         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3872
3873         nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3874         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3875         let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3876         assert_eq!(events_3.len(), 2);
3877         let as_announcement_sigs = match events_3[0] {
3878                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3879                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3880                         msg.clone()
3881                 },
3882                 _ => panic!("Unexpected event"),
3883         };
3884         let (as_announcement, as_update) = match events_3[1] {
3885                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3886                         (msg.clone(), update_msg.clone())
3887                 },
3888                 _ => panic!("Unexpected event"),
3889         };
3890
3891         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3892         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3893         assert_eq!(events_4.len(), 1);
3894         let (_, bs_update) = match events_4[0] {
3895                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3896                         (msg.clone(), update_msg.clone())
3897                 },
3898                 _ => panic!("Unexpected event"),
3899         };
3900
3901         nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3902         nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3903         nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3904
3905         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3906         let logger = test_utils::TestLogger::new();
3907         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3908         let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3909         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage, 1_000_000);
3910 }
3911
3912 #[test]
3913 fn test_drop_messages_peer_disconnect_dual_htlc() {
3914         // Test that we can handle reconnecting when both sides of a channel have pending
3915         // commitment_updates when we disconnect.
3916         let chanmon_cfgs = create_chanmon_cfgs(2);
3917         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3918         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3919         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3920         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3921         let logger = test_utils::TestLogger::new();
3922
3923         let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3924
3925         // Now try to send a second payment which will fail to send
3926         let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
3927         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3928         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3929         nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
3930         check_added_monitors!(nodes[0], 1);
3931
3932         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3933         assert_eq!(events_1.len(), 1);
3934         match events_1[0] {
3935                 MessageSendEvent::UpdateHTLCs { .. } => {},
3936                 _ => panic!("Unexpected event"),
3937         }
3938
3939         assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000));
3940         check_added_monitors!(nodes[1], 1);
3941
3942         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3943         assert_eq!(events_2.len(), 1);
3944         match events_2[0] {
3945                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
3946                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3947                         assert!(update_add_htlcs.is_empty());
3948                         assert_eq!(update_fulfill_htlcs.len(), 1);
3949                         assert!(update_fail_htlcs.is_empty());
3950                         assert!(update_fail_malformed_htlcs.is_empty());
3951                         assert!(update_fee.is_none());
3952
3953                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3954                         let events_3 = nodes[0].node.get_and_clear_pending_events();
3955                         assert_eq!(events_3.len(), 1);
3956                         match events_3[0] {
3957                                 Event::PaymentSent { ref payment_preimage } => {
3958                                         assert_eq!(*payment_preimage, payment_preimage_1);
3959                                 },
3960                                 _ => panic!("Unexpected event"),
3961                         }
3962
3963                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3964                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3965                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3966                         check_added_monitors!(nodes[0], 1);
3967                 },
3968                 _ => panic!("Unexpected event"),
3969         }
3970
3971         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3972         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3973
3974         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3975         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3976         assert_eq!(reestablish_1.len(), 1);
3977         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3978         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3979         assert_eq!(reestablish_2.len(), 1);
3980
3981         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3982         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3983         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3984         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3985
3986         assert!(as_resp.0.is_none());
3987         assert!(bs_resp.0.is_none());
3988
3989         assert!(bs_resp.1.is_none());
3990         assert!(bs_resp.2.is_none());
3991
3992         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3993
3994         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3995         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3996         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3997         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3998         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3999         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4000         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4001         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4002         // No commitment_signed so get_event_msg's assert(len == 1) passes
4003         check_added_monitors!(nodes[1], 1);
4004
4005         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4006         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4007         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4008         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4009         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4010         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4011         assert!(bs_second_commitment_signed.update_fee.is_none());
4012         check_added_monitors!(nodes[1], 1);
4013
4014         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4015         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4016         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4017         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4018         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4019         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4020         assert!(as_commitment_signed.update_fee.is_none());
4021         check_added_monitors!(nodes[0], 1);
4022
4023         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4024         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4025         // No commitment_signed so get_event_msg's assert(len == 1) passes
4026         check_added_monitors!(nodes[0], 1);
4027
4028         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4029         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4030         // No commitment_signed so get_event_msg's assert(len == 1) passes
4031         check_added_monitors!(nodes[1], 1);
4032
4033         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4034         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4035         check_added_monitors!(nodes[1], 1);
4036
4037         expect_pending_htlcs_forwardable!(nodes[1]);
4038
4039         let events_5 = nodes[1].node.get_and_clear_pending_events();
4040         assert_eq!(events_5.len(), 1);
4041         match events_5[0] {
4042                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt: _ } => {
4043                         assert_eq!(payment_hash_2, *payment_hash);
4044                         assert_eq!(*payment_secret, None);
4045                 },
4046                 _ => panic!("Unexpected event"),
4047         }
4048
4049         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4050         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4051         check_added_monitors!(nodes[0], 1);
4052
4053         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
4054 }
4055
4056 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4057         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4058         // to avoid our counterparty failing the channel.
4059         let chanmon_cfgs = create_chanmon_cfgs(2);
4060         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4061         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4062         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4063
4064         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4065         let logger = test_utils::TestLogger::new();
4066
4067         let our_payment_hash = if send_partial_mpp {
4068                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4069                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
4070                 let (_, our_payment_hash) = get_payment_preimage_hash!(&nodes[0]);
4071                 let payment_secret = PaymentSecret([0xdb; 32]);
4072                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4073                 // indicates there are more HTLCs coming.
4074                 nodes[0].node.send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200000, CHAN_CONFIRM_DEPTH).unwrap();
4075                 check_added_monitors!(nodes[0], 1);
4076                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4077                 assert_eq!(events.len(), 1);
4078                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4079                 // hop should *not* yet generate any PaymentReceived event(s).
4080                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false);
4081                 our_payment_hash
4082         } else {
4083                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4084         };
4085
4086         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4087         nodes[0].block_notifier.block_connected_checked(&header, 101, &[], &[]);
4088         nodes[1].block_notifier.block_connected_checked(&header, 101, &[], &[]);
4089         for i in 102..TEST_FINAL_CLTV + 100 + 1 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
4090                 header.prev_blockhash = header.block_hash();
4091                 nodes[0].block_notifier.block_connected_checked(&header, i, &[], &[]);
4092                 nodes[1].block_notifier.block_connected_checked(&header, i, &[], &[]);
4093         }
4094
4095         expect_pending_htlcs_forwardable!(nodes[1]);
4096
4097         check_added_monitors!(nodes[1], 1);
4098         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4099         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4100         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4101         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4102         assert!(htlc_timeout_updates.update_fee.is_none());
4103
4104         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4105         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4106         // 100_000 msat as u64, followed by a height of 123 as u32
4107         let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4108         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(123));
4109         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4110 }
4111
4112 #[test]
4113 fn test_htlc_timeout() {
4114         do_test_htlc_timeout(true);
4115         do_test_htlc_timeout(false);
4116 }
4117
4118 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4119         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4120         let chanmon_cfgs = create_chanmon_cfgs(3);
4121         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4122         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4123         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4124         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4125         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4126         let logger = test_utils::TestLogger::new();
4127
4128         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4129         let (_, first_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4130         {
4131                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4132                 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
4133                 nodes[1].node.send_payment(&route, first_payment_hash, &None).unwrap();
4134         }
4135         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4136         check_added_monitors!(nodes[1], 1);
4137
4138         // Now attempt to route a second payment, which should be placed in the holding cell
4139         let (_, second_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4140         if forwarded_htlc {
4141                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4142                 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
4143                 nodes[0].node.send_payment(&route, second_payment_hash, &None).unwrap();
4144                 check_added_monitors!(nodes[0], 1);
4145                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4146                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4147                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4148                 expect_pending_htlcs_forwardable!(nodes[1]);
4149                 check_added_monitors!(nodes[1], 0);
4150         } else {
4151                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4152                 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
4153                 nodes[1].node.send_payment(&route, second_payment_hash, &None).unwrap();
4154                 check_added_monitors!(nodes[1], 0);
4155         }
4156
4157         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4158         nodes[1].block_notifier.block_connected_checked(&header, 101, &[], &[]);
4159         for i in 102..TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
4160                 header.prev_blockhash = header.block_hash();
4161                 nodes[1].block_notifier.block_connected_checked(&header, i, &[], &[]);
4162         }
4163
4164         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4165         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4166
4167         header.prev_blockhash = header.block_hash();
4168         nodes[1].block_notifier.block_connected_checked(&header, TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS, &[], &[]);
4169
4170         if forwarded_htlc {
4171                 expect_pending_htlcs_forwardable!(nodes[1]);
4172                 check_added_monitors!(nodes[1], 1);
4173                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4174                 assert_eq!(fail_commit.len(), 1);
4175                 match fail_commit[0] {
4176                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4177                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4178                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4179                         },
4180                         _ => unreachable!(),
4181                 }
4182                 expect_payment_failed!(nodes[0], second_payment_hash, false);
4183                 if let &MessageSendEvent::PaymentFailureNetworkUpdate { ref update } = &nodes[0].node.get_and_clear_pending_msg_events()[0] {
4184                         match update {
4185                                 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {},
4186                                 _ => panic!("Unexpected event"),
4187                         }
4188                 } else {
4189                         panic!("Unexpected event");
4190                 }
4191         } else {
4192                 expect_payment_failed!(nodes[1], second_payment_hash, true);
4193         }
4194 }
4195
4196 #[test]
4197 fn test_holding_cell_htlc_add_timeouts() {
4198         do_test_holding_cell_htlc_add_timeouts(false);
4199         do_test_holding_cell_htlc_add_timeouts(true);
4200 }
4201
4202 #[test]
4203 fn test_invalid_channel_announcement() {
4204         //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
4205         let secp_ctx = Secp256k1::new();
4206         let chanmon_cfgs = create_chanmon_cfgs(2);
4207         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4208         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4209         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4210
4211         let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
4212
4213         let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
4214         let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
4215         let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4216         let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4217
4218         nodes[0].net_graph_msg_handler.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id : as_chan.get_short_channel_id().unwrap(), is_permanent: false } );
4219
4220         let as_bitcoin_key = as_chan.get_keys().inner.holder_channel_pubkeys.funding_pubkey;
4221         let bs_bitcoin_key = bs_chan.get_keys().inner.holder_channel_pubkeys.funding_pubkey;
4222
4223         let as_network_key = nodes[0].node.get_our_node_id();
4224         let bs_network_key = nodes[1].node.get_our_node_id();
4225
4226         let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
4227
4228         let mut chan_announcement;
4229
4230         macro_rules! dummy_unsigned_msg {
4231                 () => {
4232                         msgs::UnsignedChannelAnnouncement {
4233                                 features: ChannelFeatures::known(),
4234                                 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4235                                 short_channel_id: as_chan.get_short_channel_id().unwrap(),
4236                                 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
4237                                 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
4238                                 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
4239                                 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
4240                                 excess_data: Vec::new(),
4241                         };
4242                 }
4243         }
4244
4245         macro_rules! sign_msg {
4246                 ($unsigned_msg: expr) => {
4247                         let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
4248                         let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_keys().inner.funding_key);
4249                         let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_keys().inner.funding_key);
4250                         let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
4251                         let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
4252                         chan_announcement = msgs::ChannelAnnouncement {
4253                                 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
4254                                 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
4255                                 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
4256                                 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
4257                                 contents: $unsigned_msg
4258                         }
4259                 }
4260         }
4261
4262         let unsigned_msg = dummy_unsigned_msg!();
4263         sign_msg!(unsigned_msg);
4264         assert_eq!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap(), true);
4265         let _ = nodes[0].net_graph_msg_handler.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id : as_chan.get_short_channel_id().unwrap(), is_permanent: false } );
4266
4267         // Configured with Network::Testnet
4268         let mut unsigned_msg = dummy_unsigned_msg!();
4269         unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.block_hash();
4270         sign_msg!(unsigned_msg);
4271         assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4272
4273         let mut unsigned_msg = dummy_unsigned_msg!();
4274         unsigned_msg.chain_hash = BlockHash::hash(&[1,2,3,4,5,6,7,8,9]);
4275         sign_msg!(unsigned_msg);
4276         assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4277 }
4278
4279 #[test]
4280 fn test_no_txn_manager_serialize_deserialize() {
4281         let chanmon_cfgs = create_chanmon_cfgs(2);
4282         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4283         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4284         let logger: test_utils::TestLogger;
4285         let fee_estimator: test_utils::TestFeeEstimator;
4286         let new_chan_monitor: test_utils::TestChannelMonitor;
4287         let keys_manager: test_utils::TestKeysInterface;
4288         let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4289         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4290
4291         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4292
4293         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4294
4295         let nodes_0_serialized = nodes[0].node.encode();
4296         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4297         nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
4298
4299         logger = test_utils::TestLogger::new();
4300         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4301         new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator);
4302         nodes[0].chan_monitor = &new_chan_monitor;
4303         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4304         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read).unwrap();
4305         assert!(chan_0_monitor_read.is_empty());
4306
4307         let mut nodes_0_read = &nodes_0_serialized[..];
4308         let config = UserConfig::default();
4309         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4310         let (_, nodes_0_deserialized_tmp) = {
4311                 let mut channel_monitors = HashMap::new();
4312                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4313                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4314                         default_config: config,
4315                         keys_manager: &keys_manager,
4316                         fee_estimator: &fee_estimator,
4317                         monitor: nodes[0].chan_monitor,
4318                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4319                         logger: &logger,
4320                         channel_monitors,
4321                 }).unwrap()
4322         };
4323         nodes_0_deserialized = nodes_0_deserialized_tmp;
4324         assert!(nodes_0_read.is_empty());
4325
4326         assert!(nodes[0].chan_monitor.add_monitor(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4327         nodes[0].node = &nodes_0_deserialized;
4328         nodes[0].block_notifier.register_listener(nodes[0].node);
4329         assert_eq!(nodes[0].node.list_channels().len(), 1);
4330         check_added_monitors!(nodes[0], 1);
4331
4332         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4333         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4334         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4335         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4336
4337         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4338         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4339         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4340         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4341
4342         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4343         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4344         for node in nodes.iter() {
4345                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4346                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4347                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4348         }
4349
4350         send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4351 }
4352
4353 #[test]
4354 fn test_manager_serialize_deserialize_events() {
4355         // This test makes sure the events field in ChannelManager survives de/serialization
4356         let chanmon_cfgs = create_chanmon_cfgs(2);
4357         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4358         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4359         let fee_estimator: test_utils::TestFeeEstimator;
4360         let logger: test_utils::TestLogger;
4361         let new_chan_monitor: test_utils::TestChannelMonitor;
4362         let keys_manager: test_utils::TestKeysInterface;
4363         let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4364         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4365
4366         // Start creating a channel, but stop right before broadcasting the event message FundingBroadcastSafe
4367         let channel_value = 100000;
4368         let push_msat = 10001;
4369         let a_flags = InitFeatures::known();
4370         let b_flags = InitFeatures::known();
4371         let node_a = nodes.pop().unwrap();
4372         let node_b = nodes.pop().unwrap();
4373         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4374         node_b.node.handle_open_channel(&node_a.node.get_our_node_id(), a_flags, &get_event_msg!(node_a, MessageSendEvent::SendOpenChannel, node_b.node.get_our_node_id()));
4375         node_a.node.handle_accept_channel(&node_b.node.get_our_node_id(), b_flags, &get_event_msg!(node_b, MessageSendEvent::SendAcceptChannel, node_a.node.get_our_node_id()));
4376
4377         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4378
4379         node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
4380         check_added_monitors!(node_a, 0);
4381
4382         node_b.node.handle_funding_created(&node_a.node.get_our_node_id(), &get_event_msg!(node_a, MessageSendEvent::SendFundingCreated, node_b.node.get_our_node_id()));
4383         {
4384                 let mut added_monitors = node_b.chan_monitor.added_monitors.lock().unwrap();
4385                 assert_eq!(added_monitors.len(), 1);
4386                 assert_eq!(added_monitors[0].0, funding_output);
4387                 added_monitors.clear();
4388         }
4389
4390         node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id()));
4391         {
4392                 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
4393                 assert_eq!(added_monitors.len(), 1);
4394                 assert_eq!(added_monitors[0].0, funding_output);
4395                 added_monitors.clear();
4396         }
4397         // Normally, this is where node_a would check for a FundingBroadcastSafe event, but the test de/serializes first instead
4398
4399         nodes.push(node_a);
4400         nodes.push(node_b);
4401
4402         // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4403         let nodes_0_serialized = nodes[0].node.encode();
4404         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4405         nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
4406
4407         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4408         logger = test_utils::TestLogger::new();
4409         new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator);
4410         nodes[0].chan_monitor = &new_chan_monitor;
4411         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4412         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read).unwrap();
4413         assert!(chan_0_monitor_read.is_empty());
4414
4415         let mut nodes_0_read = &nodes_0_serialized[..];
4416         let config = UserConfig::default();
4417         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4418         let (_, nodes_0_deserialized_tmp) = {
4419                 let mut channel_monitors = HashMap::new();
4420                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4421                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4422                         default_config: config,
4423                         keys_manager: &keys_manager,
4424                         fee_estimator: &fee_estimator,
4425                         monitor: nodes[0].chan_monitor,
4426                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4427                         logger: &logger,
4428                         channel_monitors,
4429                 }).unwrap()
4430         };
4431         nodes_0_deserialized = nodes_0_deserialized_tmp;
4432         assert!(nodes_0_read.is_empty());
4433
4434         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4435
4436         assert!(nodes[0].chan_monitor.add_monitor(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4437         nodes[0].node = &nodes_0_deserialized;
4438
4439         // After deserializing, make sure the FundingBroadcastSafe event is still held by the channel manager
4440         let events_4 = nodes[0].node.get_and_clear_pending_events();
4441         assert_eq!(events_4.len(), 1);
4442         match events_4[0] {
4443                 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
4444                         assert_eq!(user_channel_id, 42);
4445                         assert_eq!(*funding_txo, funding_output);
4446                 },
4447                 _ => panic!("Unexpected event"),
4448         };
4449
4450         // Make sure the channel is functioning as though the de/serialization never happened
4451         nodes[0].block_notifier.register_listener(nodes[0].node);
4452         assert_eq!(nodes[0].node.list_channels().len(), 1);
4453         check_added_monitors!(nodes[0], 1);
4454
4455         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4456         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4457         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4458         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4459
4460         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4461         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4462         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4463         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4464
4465         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4466         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4467         for node in nodes.iter() {
4468                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4469                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4470                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4471         }
4472
4473         send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4474 }
4475
4476 #[test]
4477 fn test_simple_manager_serialize_deserialize() {
4478         let chanmon_cfgs = create_chanmon_cfgs(2);
4479         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4480         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4481         let logger: test_utils::TestLogger;
4482         let fee_estimator: test_utils::TestFeeEstimator;
4483         let new_chan_monitor: test_utils::TestChannelMonitor;
4484         let keys_manager: test_utils::TestKeysInterface;
4485         let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4486         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4487         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4488
4489         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4490         let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4491
4492         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4493
4494         let nodes_0_serialized = nodes[0].node.encode();
4495         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4496         nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
4497
4498         logger = test_utils::TestLogger::new();
4499         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4500         new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator);
4501         nodes[0].chan_monitor = &new_chan_monitor;
4502         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4503         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read).unwrap();
4504         assert!(chan_0_monitor_read.is_empty());
4505
4506         let mut nodes_0_read = &nodes_0_serialized[..];
4507         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4508         let (_, nodes_0_deserialized_tmp) = {
4509                 let mut channel_monitors = HashMap::new();
4510                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4511                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4512                         default_config: UserConfig::default(),
4513                         keys_manager: &keys_manager,
4514                         fee_estimator: &fee_estimator,
4515                         monitor: nodes[0].chan_monitor,
4516                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4517                         logger: &logger,
4518                         channel_monitors,
4519                 }).unwrap()
4520         };
4521         nodes_0_deserialized = nodes_0_deserialized_tmp;
4522         assert!(nodes_0_read.is_empty());
4523
4524         assert!(nodes[0].chan_monitor.add_monitor(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4525         nodes[0].node = &nodes_0_deserialized;
4526         check_added_monitors!(nodes[0], 1);
4527
4528         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4529
4530         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4531         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage, 1_000_000);
4532 }
4533
4534 #[test]
4535 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4536         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4537         let chanmon_cfgs = create_chanmon_cfgs(4);
4538         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4539         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4540         let logger: test_utils::TestLogger;
4541         let fee_estimator: test_utils::TestFeeEstimator;
4542         let new_chan_monitor: test_utils::TestChannelMonitor;
4543         let keys_manager: test_utils::TestKeysInterface;
4544         let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4545         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4546         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4547         create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known());
4548         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4549
4550         let mut node_0_stale_monitors_serialized = Vec::new();
4551         for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
4552                 let mut writer = test_utils::TestVecWriter(Vec::new());
4553                 monitor.1.write_for_disk(&mut writer).unwrap();
4554                 node_0_stale_monitors_serialized.push(writer.0);
4555         }
4556
4557         let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4558
4559         // Serialize the ChannelManager here, but the monitor we keep up-to-date
4560         let nodes_0_serialized = nodes[0].node.encode();
4561
4562         route_payment(&nodes[0], &[&nodes[3]], 1000000);
4563         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4564         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4565         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4566
4567         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4568         // nodes[3])
4569         let mut node_0_monitors_serialized = Vec::new();
4570         for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
4571                 let mut writer = test_utils::TestVecWriter(Vec::new());
4572                 monitor.1.write_for_disk(&mut writer).unwrap();
4573                 node_0_monitors_serialized.push(writer.0);
4574         }
4575
4576         logger = test_utils::TestLogger::new();
4577         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4578         new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator);
4579         nodes[0].chan_monitor = &new_chan_monitor;
4580
4581         let mut node_0_stale_monitors = Vec::new();
4582         for serialized in node_0_stale_monitors_serialized.iter() {
4583                 let mut read = &serialized[..];
4584                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read).unwrap();
4585                 assert!(read.is_empty());
4586                 node_0_stale_monitors.push(monitor);
4587         }
4588
4589         let mut node_0_monitors = Vec::new();
4590         for serialized in node_0_monitors_serialized.iter() {
4591                 let mut read = &serialized[..];
4592                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read).unwrap();
4593                 assert!(read.is_empty());
4594                 node_0_monitors.push(monitor);
4595         }
4596
4597         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4598
4599         let mut nodes_0_read = &nodes_0_serialized[..];
4600         if let Err(msgs::DecodeError::InvalidValue) =
4601                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4602                 default_config: UserConfig::default(),
4603                 keys_manager: &keys_manager,
4604                 fee_estimator: &fee_estimator,
4605                 monitor: nodes[0].chan_monitor,
4606                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4607                 logger: &logger,
4608                 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4609         }) { } else {
4610                 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4611         };
4612
4613         let mut nodes_0_read = &nodes_0_serialized[..];
4614         let (_, nodes_0_deserialized_tmp) =
4615                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4616                 default_config: UserConfig::default(),
4617                 keys_manager: &keys_manager,
4618                 fee_estimator: &fee_estimator,
4619                 monitor: nodes[0].chan_monitor,
4620                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4621                 logger: &logger,
4622                 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4623         }).unwrap();
4624         nodes_0_deserialized = nodes_0_deserialized_tmp;
4625         assert!(nodes_0_read.is_empty());
4626
4627         { // Channel close should result in a commitment tx and an HTLC tx
4628                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4629                 assert_eq!(txn.len(), 2);
4630                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4631                 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
4632         }
4633
4634         for monitor in node_0_monitors.drain(..) {
4635                 assert!(nodes[0].chan_monitor.add_monitor(monitor.get_funding_txo().0, monitor).is_ok());
4636                 check_added_monitors!(nodes[0], 1);
4637         }
4638         nodes[0].node = &nodes_0_deserialized;
4639
4640         // nodes[1] and nodes[2] have no lost state with nodes[0]...
4641         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4642         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4643         //... and we can even still claim the payment!
4644         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage, 1_000_000);
4645
4646         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4647         let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4648         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4649         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4650         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4651         assert_eq!(msg_events.len(), 1);
4652         if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4653                 match action {
4654                         &ErrorAction::SendErrorMessage { ref msg } => {
4655                                 assert_eq!(msg.channel_id, channel_id);
4656                         },
4657                         _ => panic!("Unexpected event!"),
4658                 }
4659         }
4660 }
4661
4662 macro_rules! check_spendable_outputs {
4663         ($node: expr, $der_idx: expr, $keysinterface: expr, $chan_value: expr) => {
4664                 {
4665                         let events = $node.chan_monitor.simple_monitor.get_and_clear_pending_events();
4666                         let mut txn = Vec::new();
4667                         for event in events {
4668                                 match event {
4669                                         Event::SpendableOutputs { ref outputs } => {
4670                                                 for outp in outputs {
4671                                                         match *outp {
4672                                                                 SpendableOutputDescriptor::StaticOutputCounterpartyPayment { ref outpoint, ref output, ref key_derivation_params } => {
4673                                                                         let input = TxIn {
4674                                                                                 previous_output: outpoint.into_bitcoin_outpoint(),
4675                                                                                 script_sig: Script::new(),
4676                                                                                 sequence: 0,
4677                                                                                 witness: Vec::new(),
4678                                                                         };
4679                                                                         let outp = TxOut {
4680                                                                                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4681                                                                                 value: output.value,
4682                                                                         };
4683                                                                         let mut spend_tx = Transaction {
4684                                                                                 version: 2,
4685                                                                                 lock_time: 0,
4686                                                                                 input: vec![input],
4687                                                                                 output: vec![outp],
4688                                                                         };
4689                                                                         let secp_ctx = Secp256k1::new();
4690                                                                         let keys = $keysinterface.derive_channel_keys($chan_value, key_derivation_params.0, key_derivation_params.1);
4691                                                                         let remotepubkey = keys.pubkeys().payment_point;
4692                                                                         let witness_script = Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: remotepubkey}, Network::Testnet).script_pubkey();
4693                                                                         let sighash = Message::from_slice(&bip143::SigHashCache::new(&spend_tx).signature_hash(0, &witness_script, output.value, SigHashType::All)[..]).unwrap();
4694                                                                         let remotesig = secp_ctx.sign(&sighash, &keys.inner.payment_key);
4695                                                                         spend_tx.input[0].witness.push(remotesig.serialize_der().to_vec());
4696                                                                         spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4697                                                                         spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
4698                                                                         txn.push(spend_tx);
4699                                                                 },
4700                                                                 SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref per_commitment_point, ref to_self_delay, ref output, ref key_derivation_params, ref revocation_pubkey } => {
4701                                                                         let input = TxIn {
4702                                                                                 previous_output: outpoint.into_bitcoin_outpoint(),
4703                                                                                 script_sig: Script::new(),
4704                                                                                 sequence: *to_self_delay as u32,
4705                                                                                 witness: Vec::new(),
4706                                                                         };
4707                                                                         let outp = TxOut {
4708                                                                                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4709                                                                                 value: output.value,
4710                                                                         };
4711                                                                         let mut spend_tx = Transaction {
4712                                                                                 version: 2,
4713                                                                                 lock_time: 0,
4714                                                                                 input: vec![input],
4715                                                                                 output: vec![outp],
4716                                                                         };
4717                                                                         let secp_ctx = Secp256k1::new();
4718                                                                         let keys = $keysinterface.derive_channel_keys($chan_value, key_derivation_params.0, key_derivation_params.1);
4719                                                                         if let Ok(delayed_payment_key) = chan_utils::derive_private_key(&secp_ctx, &per_commitment_point, &keys.inner.delayed_payment_base_key) {
4720
4721                                                                                 let delayed_payment_pubkey = PublicKey::from_secret_key(&secp_ctx, &delayed_payment_key);
4722                                                                                 let witness_script = chan_utils::get_revokeable_redeemscript(revocation_pubkey, *to_self_delay, &delayed_payment_pubkey);
4723                                                                                 let sighash = Message::from_slice(&bip143::SigHashCache::new(&spend_tx).signature_hash(0, &witness_script, output.value, SigHashType::All)[..]).unwrap();
4724                                                                                 let local_delayedsig = secp_ctx.sign(&sighash, &delayed_payment_key);
4725                                                                                 spend_tx.input[0].witness.push(local_delayedsig.serialize_der().to_vec());
4726                                                                                 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4727                                                                                 spend_tx.input[0].witness.push(vec!()); //MINIMALIF
4728                                                                                 spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
4729                                                                         } else { panic!() }
4730                                                                         txn.push(spend_tx);
4731                                                                 },
4732                                                                 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
4733                                                                         let secp_ctx = Secp256k1::new();
4734                                                                         let input = TxIn {
4735                                                                                 previous_output: outpoint.into_bitcoin_outpoint(),
4736                                                                                 script_sig: Script::new(),
4737                                                                                 sequence: 0,
4738                                                                                 witness: Vec::new(),
4739                                                                         };
4740                                                                         let outp = TxOut {
4741                                                                                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4742                                                                                 value: output.value,
4743                                                                         };
4744                                                                         let mut spend_tx = Transaction {
4745                                                                                 version: 2,
4746                                                                                 lock_time: 0,
4747                                                                                 input: vec![input],
4748                                                                                 output: vec![outp.clone()],
4749                                                                         };
4750                                                                         let secret = {
4751                                                                                 match ExtendedPrivKey::new_master(Network::Testnet, &$node.node_seed) {
4752                                                                                         Ok(master_key) => {
4753                                                                                                 match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx).expect("key space exhausted")) {
4754                                                                                                         Ok(key) => key,
4755                                                                                                         Err(_) => panic!("Your RNG is busted"),
4756                                                                                                 }
4757                                                                                         }
4758                                                                                         Err(_) => panic!("Your rng is busted"),
4759                                                                                 }
4760                                                                         };
4761                                                                         let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
4762                                                                         let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
4763                                                                         let sighash = Message::from_slice(&bip143::SigHashCache::new(&spend_tx).signature_hash(0, &witness_script, output.value, SigHashType::All)[..]).unwrap();
4764                                                                         let sig = secp_ctx.sign(&sighash, &secret.private_key.key);
4765                                                                         spend_tx.input[0].witness.push(sig.serialize_der().to_vec());
4766                                                                         spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4767                                                                         spend_tx.input[0].witness.push(pubkey.key.serialize().to_vec());
4768                                                                         txn.push(spend_tx);
4769                                                                 },
4770                                                         }
4771                                                 }
4772                                         },
4773                                         _ => panic!("Unexpected event"),
4774                                 };
4775                         }
4776                         txn
4777                 }
4778         }
4779 }
4780
4781 #[test]
4782 fn test_claim_sizeable_push_msat() {
4783         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4784         let chanmon_cfgs = create_chanmon_cfgs(2);
4785         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4786         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4787         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4788
4789         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4790         nodes[1].node.force_close_channel(&chan.2);
4791         check_closed_broadcast!(nodes[1], false);
4792         check_added_monitors!(nodes[1], 1);
4793         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4794         assert_eq!(node_txn.len(), 1);
4795         check_spends!(node_txn[0], chan.3);
4796         assert_eq!(node_txn[0].output.len(), 2); // We can't force trimming of to_remote output as channel_reserve_satoshis block us to do so at channel opening
4797
4798         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4799         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4800         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4801
4802         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4803         assert_eq!(spend_txn.len(), 1);
4804         check_spends!(spend_txn[0], node_txn[0]);
4805 }
4806
4807 #[test]
4808 fn test_claim_on_remote_sizeable_push_msat() {
4809         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4810         // to_remote output is encumbered by a P2WPKH
4811         let chanmon_cfgs = create_chanmon_cfgs(2);
4812         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4813         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4814         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4815
4816         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4817         nodes[0].node.force_close_channel(&chan.2);
4818         check_closed_broadcast!(nodes[0], false);
4819         check_added_monitors!(nodes[0], 1);
4820
4821         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4822         assert_eq!(node_txn.len(), 1);
4823         check_spends!(node_txn[0], chan.3);
4824         assert_eq!(node_txn[0].output.len(), 2); // We can't force trimming of to_remote output as channel_reserve_satoshis block us to do so at channel opening
4825
4826         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4827         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4828         check_closed_broadcast!(nodes[1], false);
4829         check_added_monitors!(nodes[1], 1);
4830         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4831
4832         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4833         assert_eq!(spend_txn.len(), 2);
4834         assert_eq!(spend_txn[0], spend_txn[1]);
4835         check_spends!(spend_txn[0], node_txn[0]);
4836 }
4837
4838 #[test]
4839 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4840         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4841         // to_remote output is encumbered by a P2WPKH
4842
4843         let chanmon_cfgs = create_chanmon_cfgs(2);
4844         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4845         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4846         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4847
4848         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4849         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4850         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4851         assert_eq!(revoked_local_txn[0].input.len(), 1);
4852         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4853
4854         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4855         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4856         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
4857         check_closed_broadcast!(nodes[1], false);
4858         check_added_monitors!(nodes[1], 1);
4859
4860         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4861         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4862         nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4863         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4864
4865         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4866         assert_eq!(spend_txn.len(), 3);
4867         assert_eq!(spend_txn[0], spend_txn[1]); // to_remote output on revoked remote commitment_tx
4868         check_spends!(spend_txn[0], revoked_local_txn[0]);
4869         check_spends!(spend_txn[2], node_txn[0]);
4870 }
4871
4872 #[test]
4873 fn test_static_spendable_outputs_preimage_tx() {
4874         let chanmon_cfgs = create_chanmon_cfgs(2);
4875         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4876         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4877         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4878
4879         // Create some initial channels
4880         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4881
4882         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4883
4884         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4885         assert_eq!(commitment_tx[0].input.len(), 1);
4886         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4887
4888         // Settle A's commitment tx on B's chain
4889         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4890         assert!(nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000));
4891         check_added_monitors!(nodes[1], 1);
4892         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
4893         check_added_monitors!(nodes[1], 1);
4894         let events = nodes[1].node.get_and_clear_pending_msg_events();
4895         match events[0] {
4896                 MessageSendEvent::UpdateHTLCs { .. } => {},
4897                 _ => panic!("Unexpected event"),
4898         }
4899         match events[1] {
4900                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4901                 _ => panic!("Unexepected event"),
4902         }
4903
4904         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4905         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4906         assert_eq!(node_txn.len(), 3);
4907         check_spends!(node_txn[0], commitment_tx[0]);
4908         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4909         check_spends!(node_txn[1], chan_1.3);
4910         check_spends!(node_txn[2], node_txn[1]);
4911
4912         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4913         nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4914         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4915
4916         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4917         assert_eq!(spend_txn.len(), 1);
4918         check_spends!(spend_txn[0], node_txn[0]);
4919 }
4920
4921 #[test]
4922 fn test_static_spendable_outputs_timeout_tx() {
4923         let chanmon_cfgs = create_chanmon_cfgs(2);
4924         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4925         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4926         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4927
4928         // Create some initial channels
4929         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4930
4931         // Rebalance the network a bit by relaying one payment through all the channels ...
4932         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
4933
4934         let (_, our_payment_hash) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4935
4936         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4937         assert_eq!(commitment_tx[0].input.len(), 1);
4938         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4939
4940         // Settle A's commitment tx on B' chain
4941         let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
4942         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 0);
4943         check_added_monitors!(nodes[1], 1);
4944         let events = nodes[1].node.get_and_clear_pending_msg_events();
4945         match events[0] {
4946                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4947                 _ => panic!("Unexpected event"),
4948         }
4949
4950         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4951         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4952         assert_eq!(node_txn.len(), 3); // ChannelManager : 2 (local commitent tx + HTLC-timeout), ChannelMonitor: timeout tx
4953         check_spends!(node_txn[0],  commitment_tx[0].clone());
4954         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4955         check_spends!(node_txn[1], chan_1.3.clone());
4956         check_spends!(node_txn[2], node_txn[1]);
4957
4958         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4959         nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4960         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4961         expect_payment_failed!(nodes[1], our_payment_hash, true);
4962
4963         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4964         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote (*2), timeout_tx.output (*1)
4965         check_spends!(spend_txn[2], node_txn[0].clone());
4966 }
4967
4968 #[test]
4969 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4970         let chanmon_cfgs = create_chanmon_cfgs(2);
4971         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4972         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4973         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4974
4975         // Create some initial channels
4976         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4977
4978         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4979         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4980         assert_eq!(revoked_local_txn[0].input.len(), 1);
4981         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4982
4983         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4984
4985         let  header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4986         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
4987         check_closed_broadcast!(nodes[1], false);
4988         check_added_monitors!(nodes[1], 1);
4989
4990         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4991         assert_eq!(node_txn.len(), 2);
4992         assert_eq!(node_txn[0].input.len(), 2);
4993         check_spends!(node_txn[0], revoked_local_txn[0]);
4994
4995         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4996         nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4997         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4998
4999         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5000         assert_eq!(spend_txn.len(), 1);
5001         check_spends!(spend_txn[0], node_txn[0]);
5002 }
5003
5004 #[test]
5005 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
5006         let chanmon_cfgs = create_chanmon_cfgs(2);
5007         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5008         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5009         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5010
5011         // Create some initial channels
5012         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5013
5014         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5015         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5016         assert_eq!(revoked_local_txn[0].input.len(), 1);
5017         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5018
5019         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
5020
5021         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5022         // A will generate HTLC-Timeout from revoked commitment tx
5023         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5024         check_closed_broadcast!(nodes[0], false);
5025         check_added_monitors!(nodes[0], 1);
5026
5027         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5028         assert_eq!(revoked_htlc_txn.len(), 2);
5029         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5030         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5031         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5032         check_spends!(revoked_htlc_txn[1], chan_1.3);
5033
5034         // B will generate justice tx from A's revoked commitment/HTLC tx
5035         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 0);
5036         check_closed_broadcast!(nodes[1], false);
5037         check_added_monitors!(nodes[1], 1);
5038
5039         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5040         assert_eq!(node_txn.len(), 4); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-timeout, adjusted justice tx, ChannelManager: local commitment tx
5041         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5042         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5043         // transactions next...
5044         assert_eq!(node_txn[0].input.len(), 2);
5045         check_spends!(node_txn[0], revoked_local_txn[0]);
5046
5047         check_spends!(node_txn[1], chan_1.3);
5048
5049         assert_eq!(node_txn[2].input.len(), 1);
5050         check_spends!(node_txn[2], revoked_htlc_txn[0]);
5051         assert_eq!(node_txn[3].input.len(), 1);
5052         check_spends!(node_txn[3], revoked_local_txn[0]);
5053
5054         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5055         nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[2].clone(), node_txn[3].clone()] }, 1);
5056         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5057
5058         // Note that nodes[1]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5059         // didn't try to generate any new transactions.
5060
5061         // Check B's ChannelMonitor was able to generate the right spendable output descriptor which
5062         // allows the user to spend the newly-confirmed outputs.
5063         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5064         assert_eq!(spend_txn.len(), 2);
5065         check_spends!(spend_txn[0], node_txn[2]);
5066         check_spends!(spend_txn[1], node_txn[3]);
5067 }
5068
5069 #[test]
5070 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
5071         let chanmon_cfgs = create_chanmon_cfgs(2);
5072         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5073         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5074         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5075
5076         // Create some initial channels
5077         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5078
5079         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5080         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5081         assert_eq!(revoked_local_txn[0].input.len(), 1);
5082         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5083
5084         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
5085         assert_eq!(revoked_local_txn[0].output.len(), 2);
5086
5087         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
5088
5089         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5090         // B will generate HTLC-Success from revoked commitment tx
5091         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5092         check_closed_broadcast!(nodes[1], false);
5093         check_added_monitors!(nodes[1], 1);
5094         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5095
5096         assert_eq!(revoked_htlc_txn.len(), 2);
5097         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5098         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5099         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5100
5101         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5102         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5103         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5104
5105         // A will generate justice tx from B's revoked commitment/HTLC tx
5106         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
5107         check_closed_broadcast!(nodes[0], false);
5108         check_added_monitors!(nodes[0], 1);
5109
5110         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5111         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5112
5113         // The first transaction generated is just in case of a reorg - it double-spends
5114         // revoked_htlc_txn[0], spending the HTLC output on revoked_local_txn[0] directly.
5115         assert_eq!(node_txn[0].input.len(), 1);
5116         check_spends!(node_txn[0], revoked_local_txn[0]);
5117         assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5118
5119         assert_eq!(node_txn[2].input.len(), 1);
5120         check_spends!(node_txn[2], revoked_htlc_txn[0]);
5121
5122         check_spends!(node_txn[1], chan_1.3);
5123
5124         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5125         nodes[0].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[2].clone()] }, 1);
5126         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5127
5128         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5129         // didn't try to generate any new transactions.
5130
5131         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5132         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5133         assert_eq!(spend_txn.len(), 4); // Duplicated SpendableOutput due to block rescan after revoked htlc output tracking
5134         assert_eq!(spend_txn[0], spend_txn[1]);
5135         assert_eq!(spend_txn[0], spend_txn[2]);
5136         assert_eq!(spend_txn[0].input.len(), 1);
5137         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5138         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5139         check_spends!(spend_txn[3], node_txn[2]); // spending justice tx output on the htlc success tx
5140 }
5141
5142 #[test]
5143 fn test_onchain_to_onchain_claim() {
5144         // Test that in case of channel closure, we detect the state of output thanks to
5145         // ChainWatchInterface and claim HTLC on downstream peer's remote commitment tx.
5146         // First, have C claim an HTLC against its own latest commitment transaction.
5147         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5148         // channel.
5149         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5150         // gets broadcast.
5151
5152         let chanmon_cfgs = create_chanmon_cfgs(3);
5153         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5154         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5155         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5156
5157         // Create some initial channels
5158         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5159         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5160
5161         // Rebalance the network a bit by relaying one payment through all the channels ...
5162         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5163         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5164
5165         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5166         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5167         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5168         check_spends!(commitment_tx[0], chan_2.3);
5169         nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000);
5170         check_added_monitors!(nodes[2], 1);
5171         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5172         assert!(updates.update_add_htlcs.is_empty());
5173         assert!(updates.update_fail_htlcs.is_empty());
5174         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5175         assert!(updates.update_fail_malformed_htlcs.is_empty());
5176
5177         nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
5178         check_closed_broadcast!(nodes[2], false);
5179         check_added_monitors!(nodes[2], 1);
5180
5181         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5182         assert_eq!(c_txn.len(), 3);
5183         assert_eq!(c_txn[0], c_txn[2]);
5184         assert_eq!(commitment_tx[0], c_txn[1]);
5185         check_spends!(c_txn[1], chan_2.3);
5186         check_spends!(c_txn[2], c_txn[1]);
5187         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5188         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5189         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5190         assert_eq!(c_txn[0].lock_time, 0); // Success tx
5191
5192         // 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
5193         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
5194         {
5195                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5196                 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-timeout tx
5197                 assert_eq!(b_txn.len(), 3);
5198                 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
5199                 check_spends!(b_txn[2], b_txn[1]); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
5200                 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5201                 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5202                 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5203                 check_spends!(b_txn[0], c_txn[1]); // timeout tx on C remote commitment tx, issued by ChannelMonitor, * 2 due to block rescan
5204                 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5205                 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5206                 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5207                 b_txn.clear();
5208         }
5209         check_added_monitors!(nodes[1], 1);
5210         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5211         check_added_monitors!(nodes[1], 1);
5212         match msg_events[0] {
5213                 MessageSendEvent::BroadcastChannelUpdate {  .. } => {},
5214                 _ => panic!("Unexpected event"),
5215         }
5216         match msg_events[1] {
5217                 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, .. } } => {
5218                         assert!(update_add_htlcs.is_empty());
5219                         assert!(update_fail_htlcs.is_empty());
5220                         assert_eq!(update_fulfill_htlcs.len(), 1);
5221                         assert!(update_fail_malformed_htlcs.is_empty());
5222                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5223                 },
5224                 _ => panic!("Unexpected event"),
5225         };
5226         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5227         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5228         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
5229         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5230         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5231         assert_eq!(b_txn.len(), 3);
5232         check_spends!(b_txn[1], chan_1.3);
5233         check_spends!(b_txn[2], b_txn[1]);
5234         check_spends!(b_txn[0], commitment_tx[0]);
5235         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5236         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5237         assert_eq!(b_txn[0].lock_time, 0); // Success tx
5238
5239         check_closed_broadcast!(nodes[1], false);
5240         check_added_monitors!(nodes[1], 1);
5241 }
5242
5243 #[test]
5244 fn test_duplicate_payment_hash_one_failure_one_success() {
5245         // Topology : A --> B --> C
5246         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5247         let chanmon_cfgs = create_chanmon_cfgs(3);
5248         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5249         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5250         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5251
5252         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5253         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5254
5255         let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5256         *nodes[0].network_payment_count.borrow_mut() -= 1;
5257         assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
5258
5259         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5260         assert_eq!(commitment_txn[0].input.len(), 1);
5261         check_spends!(commitment_txn[0], chan_2.3);
5262
5263         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5264         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
5265         check_closed_broadcast!(nodes[1], false);
5266         check_added_monitors!(nodes[1], 1);
5267
5268         let htlc_timeout_tx;
5269         { // Extract one of the two HTLC-Timeout transaction
5270                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5271                 // ChannelMonitor: timeout tx * 2, ChannelManager: local commitment tx + HTLC-timeout * 2
5272                 assert_eq!(node_txn.len(), 5);
5273                 check_spends!(node_txn[0], commitment_txn[0]);
5274                 assert_eq!(node_txn[0].input.len(), 1);
5275                 check_spends!(node_txn[1], commitment_txn[0]);
5276                 assert_eq!(node_txn[1].input.len(), 1);
5277                 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
5278                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5279                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5280                 check_spends!(node_txn[2], chan_2.3);
5281                 check_spends!(node_txn[3], node_txn[2]);
5282                 check_spends!(node_txn[4], node_txn[2]);
5283                 htlc_timeout_tx = node_txn[1].clone();
5284         }
5285
5286         nodes[2].node.claim_funds(our_payment_preimage, &None, 900_000);
5287         nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
5288         check_added_monitors!(nodes[2], 3);
5289         let events = nodes[2].node.get_and_clear_pending_msg_events();
5290         match events[0] {
5291                 MessageSendEvent::UpdateHTLCs { .. } => {},
5292                 _ => panic!("Unexpected event"),
5293         }
5294         match events[1] {
5295                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5296                 _ => panic!("Unexepected event"),
5297         }
5298         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5299         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)
5300         check_spends!(htlc_success_txn[2], chan_2.3);
5301         check_spends!(htlc_success_txn[3], htlc_success_txn[2]);
5302         check_spends!(htlc_success_txn[4], htlc_success_txn[2]);
5303         assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
5304         assert_eq!(htlc_success_txn[0].input.len(), 1);
5305         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5306         assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
5307         assert_eq!(htlc_success_txn[1].input.len(), 1);
5308         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5309         assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
5310         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5311         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5312
5313         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![htlc_timeout_tx] }, 200);
5314         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 200, true, header.block_hash());
5315         expect_pending_htlcs_forwardable!(nodes[1]);
5316         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5317         assert!(htlc_updates.update_add_htlcs.is_empty());
5318         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5319         assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
5320         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5321         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5322         check_added_monitors!(nodes[1], 1);
5323
5324         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5325         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5326         {
5327                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5328                 let events = nodes[0].node.get_and_clear_pending_msg_events();
5329                 assert_eq!(events.len(), 1);
5330                 match events[0] {
5331                         MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. }  } => {
5332                         },
5333                         _ => { panic!("Unexpected event"); }
5334                 }
5335         }
5336         expect_payment_failed!(nodes[0], duplicate_payment_hash, false);
5337
5338         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5339         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
5340         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5341         assert!(updates.update_add_htlcs.is_empty());
5342         assert!(updates.update_fail_htlcs.is_empty());
5343         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5344         assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
5345         assert!(updates.update_fail_malformed_htlcs.is_empty());
5346         check_added_monitors!(nodes[1], 1);
5347
5348         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5349         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5350
5351         let events = nodes[0].node.get_and_clear_pending_events();
5352         match events[0] {
5353                 Event::PaymentSent { ref payment_preimage } => {
5354                         assert_eq!(*payment_preimage, our_payment_preimage);
5355                 }
5356                 _ => panic!("Unexpected event"),
5357         }
5358 }
5359
5360 #[test]
5361 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5362         let chanmon_cfgs = create_chanmon_cfgs(2);
5363         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5364         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5365         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5366
5367         // Create some initial channels
5368         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5369
5370         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5371         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5372         assert_eq!(local_txn[0].input.len(), 1);
5373         check_spends!(local_txn[0], chan_1.3);
5374
5375         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5376         nodes[1].node.claim_funds(payment_preimage, &None, 9_000_000);
5377         check_added_monitors!(nodes[1], 1);
5378         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5379         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![local_txn[0].clone()] }, 1);
5380         check_added_monitors!(nodes[1], 1);
5381         let events = nodes[1].node.get_and_clear_pending_msg_events();
5382         match events[0] {
5383                 MessageSendEvent::UpdateHTLCs { .. } => {},
5384                 _ => panic!("Unexpected event"),
5385         }
5386         match events[1] {
5387                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5388                 _ => panic!("Unexepected event"),
5389         }
5390         let node_txn = {
5391                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5392                 assert_eq!(node_txn[0].input.len(), 1);
5393                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5394                 check_spends!(node_txn[0], local_txn[0]);
5395                 vec![node_txn[0].clone(), node_txn[2].clone()]
5396         };
5397
5398         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5399         nodes[1].block_notifier.block_connected(&Block { header: header_201, txdata: node_txn.clone() }, 201);
5400         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5401
5402         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5403         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5404         assert_eq!(spend_txn.len(), 2);
5405         check_spends!(spend_txn[0], node_txn[0]);
5406         check_spends!(spend_txn[1], node_txn[1]);
5407 }
5408
5409 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5410         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5411         // unrevoked commitment transaction.
5412         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5413         // a remote RAA before they could be failed backwards (and combinations thereof).
5414         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5415         // use the same payment hashes.
5416         // Thus, we use a six-node network:
5417         //
5418         // A \         / E
5419         //    - C - D -
5420         // B /         \ F
5421         // And test where C fails back to A/B when D announces its latest commitment transaction
5422         let chanmon_cfgs = create_chanmon_cfgs(6);
5423         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5424         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
5425         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5426         let logger = test_utils::TestLogger::new();
5427
5428         create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5429         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5430         let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5431         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5432         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5433
5434         // Rebalance and check output sanity...
5435         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000, 500_000);
5436         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000, 500_000);
5437         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5438
5439         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5440         // 0th HTLC:
5441         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
5442         // 1st HTLC:
5443         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
5444         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
5445         let our_node_id = &nodes[1].node.get_our_node_id();
5446         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();
5447         // 2nd HTLC:
5448         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
5449         // 3rd HTLC:
5450         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
5451         // 4th HTLC:
5452         let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5453         // 5th HTLC:
5454         let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5455         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();
5456         // 6th HTLC:
5457         send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
5458         // 7th HTLC:
5459         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
5460
5461         // 8th HTLC:
5462         let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5463         // 9th HTLC:
5464         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();
5465         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
5466
5467         // 10th HTLC:
5468         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
5469         // 11th HTLC:
5470         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();
5471         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
5472
5473         // Double-check that six of the new HTLC were added
5474         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5475         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5476         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5477         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5478
5479         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5480         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5481         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1, &None));
5482         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3, &None));
5483         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5, &None));
5484         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6, &None));
5485         check_added_monitors!(nodes[4], 0);
5486         expect_pending_htlcs_forwardable!(nodes[4]);
5487         check_added_monitors!(nodes[4], 1);
5488
5489         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5490         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5491         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5492         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5493         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5494         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5495
5496         // Fail 3rd below-dust and 7th above-dust HTLCs
5497         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2, &None));
5498         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4, &None));
5499         check_added_monitors!(nodes[5], 0);
5500         expect_pending_htlcs_forwardable!(nodes[5]);
5501         check_added_monitors!(nodes[5], 1);
5502
5503         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5504         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5505         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5506         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5507
5508         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5509
5510         expect_pending_htlcs_forwardable!(nodes[3]);
5511         check_added_monitors!(nodes[3], 1);
5512         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5513         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5514         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5515         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5516         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5517         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5518         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5519         if deliver_last_raa {
5520                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5521         } else {
5522                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5523         }
5524
5525         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5526         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5527         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5528         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5529         //
5530         // We now broadcast the latest commitment transaction, which *should* result in failures for
5531         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5532         // the non-broadcast above-dust HTLCs.
5533         //
5534         // Alternatively, we may broadcast the previous commitment transaction, which should only
5535         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5536         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5537
5538         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5539         if announce_latest {
5540                 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![ds_last_commitment_tx[0].clone()]}, 1);
5541         } else {
5542                 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![ds_prev_commitment_tx[0].clone()]}, 1);
5543         }
5544         connect_blocks(&nodes[2].block_notifier, ANTI_REORG_DELAY - 1, 1, true,  header.block_hash());
5545         check_closed_broadcast!(nodes[2], false);
5546         expect_pending_htlcs_forwardable!(nodes[2]);
5547         check_added_monitors!(nodes[2], 3);
5548
5549         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5550         assert_eq!(cs_msgs.len(), 2);
5551         let mut a_done = false;
5552         for msg in cs_msgs {
5553                 match msg {
5554                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5555                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5556                                 // should be failed-backwards here.
5557                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5558                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5559                                         for htlc in &updates.update_fail_htlcs {
5560                                                 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 });
5561                                         }
5562                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5563                                         assert!(!a_done);
5564                                         a_done = true;
5565                                         &nodes[0]
5566                                 } else {
5567                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5568                                         for htlc in &updates.update_fail_htlcs {
5569                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5570                                         }
5571                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5572                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5573                                         &nodes[1]
5574                                 };
5575                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5576                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5577                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5578                                 if announce_latest {
5579                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5580                                         if *node_id == nodes[0].node.get_our_node_id() {
5581                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5582                                         }
5583                                 }
5584                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5585                         },
5586                         _ => panic!("Unexpected event"),
5587                 }
5588         }
5589
5590         let as_events = nodes[0].node.get_and_clear_pending_events();
5591         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5592         let mut as_failds = HashSet::new();
5593         for event in as_events.iter() {
5594                 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5595                         assert!(as_failds.insert(*payment_hash));
5596                         if *payment_hash != payment_hash_2 {
5597                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5598                         } else {
5599                                 assert!(!rejected_by_dest);
5600                         }
5601                 } else { panic!("Unexpected event"); }
5602         }
5603         assert!(as_failds.contains(&payment_hash_1));
5604         assert!(as_failds.contains(&payment_hash_2));
5605         if announce_latest {
5606                 assert!(as_failds.contains(&payment_hash_3));
5607                 assert!(as_failds.contains(&payment_hash_5));
5608         }
5609         assert!(as_failds.contains(&payment_hash_6));
5610
5611         let bs_events = nodes[1].node.get_and_clear_pending_events();
5612         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5613         let mut bs_failds = HashSet::new();
5614         for event in bs_events.iter() {
5615                 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5616                         assert!(bs_failds.insert(*payment_hash));
5617                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5618                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5619                         } else {
5620                                 assert!(!rejected_by_dest);
5621                         }
5622                 } else { panic!("Unexpected event"); }
5623         }
5624         assert!(bs_failds.contains(&payment_hash_1));
5625         assert!(bs_failds.contains(&payment_hash_2));
5626         if announce_latest {
5627                 assert!(bs_failds.contains(&payment_hash_4));
5628         }
5629         assert!(bs_failds.contains(&payment_hash_5));
5630
5631         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5632         // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
5633         // to unknown-preimage-etc, B should have gotten 2. Thus, in the
5634         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
5635         // PaymentFailureNetworkUpdates.
5636         let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
5637         assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5638         let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5639         assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5640         for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
5641                 match event {
5642                         &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
5643                         _ => panic!("Unexpected event"),
5644                 }
5645         }
5646 }
5647
5648 #[test]
5649 fn test_fail_backwards_latest_remote_announce_a() {
5650         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5651 }
5652
5653 #[test]
5654 fn test_fail_backwards_latest_remote_announce_b() {
5655         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5656 }
5657
5658 #[test]
5659 fn test_fail_backwards_previous_remote_announce() {
5660         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5661         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5662         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5663 }
5664
5665 #[test]
5666 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5667         let chanmon_cfgs = create_chanmon_cfgs(2);
5668         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5669         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5670         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5671
5672         // Create some initial channels
5673         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5674
5675         let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5676         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5677         assert_eq!(local_txn[0].input.len(), 1);
5678         check_spends!(local_txn[0], chan_1.3);
5679
5680         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5681         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5682         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![local_txn[0].clone()] }, 200);
5683         check_closed_broadcast!(nodes[0], false);
5684         check_added_monitors!(nodes[0], 1);
5685
5686         let htlc_timeout = {
5687                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5688                 assert_eq!(node_txn[0].input.len(), 1);
5689                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5690                 check_spends!(node_txn[0], local_txn[0]);
5691                 node_txn[0].clone()
5692         };
5693
5694         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5695         nodes[0].block_notifier.block_connected(&Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
5696         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5697         expect_payment_failed!(nodes[0], our_payment_hash, true);
5698
5699         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5700         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5701         assert_eq!(spend_txn.len(), 3);
5702         assert_eq!(spend_txn[0], spend_txn[1]);
5703         check_spends!(spend_txn[0], local_txn[0]);
5704         check_spends!(spend_txn[2], htlc_timeout);
5705 }
5706
5707 #[test]
5708 fn test_key_derivation_params() {
5709         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5710         // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5711         // let us re-derive the channel key set to then derive a delayed_payment_key.
5712
5713         let chanmon_cfgs = create_chanmon_cfgs(3);
5714
5715         // We manually create the node configuration to backup the seed.
5716         let seed = [42; 32];
5717         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5718         let 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);
5719         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 };
5720         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5721         node_cfgs.remove(0);
5722         node_cfgs.insert(0, node);
5723
5724         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5725         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5726
5727         // Create some initial channels
5728         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5729         // for node 0
5730         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5731         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5732         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5733
5734         let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5735         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5736         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5737         assert_eq!(local_txn_1[0].input.len(), 1);
5738         check_spends!(local_txn_1[0], chan_1.3);
5739
5740         // We check funding pubkey are unique
5741         let (from_0_funding_key_0, from_0_funding_key_1) = (PublicKey::from_slice(&local_txn_0[0].input[0].witness[3][2..35]), PublicKey::from_slice(&local_txn_0[0].input[0].witness[3][36..69]));
5742         let (from_1_funding_key_0, from_1_funding_key_1) = (PublicKey::from_slice(&local_txn_1[0].input[0].witness[3][2..35]), PublicKey::from_slice(&local_txn_1[0].input[0].witness[3][36..69]));
5743         if from_0_funding_key_0 == from_1_funding_key_0
5744             || from_0_funding_key_0 == from_1_funding_key_1
5745             || from_0_funding_key_1 == from_1_funding_key_0
5746             || from_0_funding_key_1 == from_1_funding_key_1 {
5747                 panic!("Funding pubkeys aren't unique");
5748         }
5749
5750         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5751         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5752         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![local_txn_1[0].clone()] }, 200);
5753         check_closed_broadcast!(nodes[0], false);
5754         check_added_monitors!(nodes[0], 1);
5755
5756         let htlc_timeout = {
5757                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5758                 assert_eq!(node_txn[0].input.len(), 1);
5759                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5760                 check_spends!(node_txn[0], local_txn_1[0]);
5761                 node_txn[0].clone()
5762         };
5763
5764         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5765         nodes[0].block_notifier.block_connected(&Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
5766         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5767         expect_payment_failed!(nodes[0], our_payment_hash, true);
5768
5769         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5770         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5771         let spend_txn = check_spendable_outputs!(nodes[0], 1, new_keys_manager, 100000);
5772         assert_eq!(spend_txn.len(), 3);
5773         assert_eq!(spend_txn[0], spend_txn[1]);
5774         check_spends!(spend_txn[0], local_txn_1[0]);
5775         check_spends!(spend_txn[2], htlc_timeout);
5776 }
5777
5778 #[test]
5779 fn test_static_output_closing_tx() {
5780         let chanmon_cfgs = create_chanmon_cfgs(2);
5781         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5782         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5783         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5784
5785         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5786
5787         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
5788         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5789
5790         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5791         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![closing_tx.clone()] }, 0);
5792         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
5793
5794         let spend_txn = check_spendable_outputs!(nodes[0], 2, node_cfgs[0].keys_manager, 100000);
5795         assert_eq!(spend_txn.len(), 1);
5796         check_spends!(spend_txn[0], closing_tx);
5797
5798         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![closing_tx.clone()] }, 0);
5799         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
5800
5801         let spend_txn = check_spendable_outputs!(nodes[1], 2, node_cfgs[1].keys_manager, 100000);
5802         assert_eq!(spend_txn.len(), 1);
5803         check_spends!(spend_txn[0], closing_tx);
5804 }
5805
5806 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5807         let chanmon_cfgs = create_chanmon_cfgs(2);
5808         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5809         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5810         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5811         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5812
5813         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5814
5815         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5816         // present in B's local commitment transaction, but none of A's commitment transactions.
5817         assert!(nodes[1].node.claim_funds(our_payment_preimage, &None, if use_dust { 50_000 } else { 3_000_000 }));
5818         check_added_monitors!(nodes[1], 1);
5819
5820         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5821         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5822         let events = nodes[0].node.get_and_clear_pending_events();
5823         assert_eq!(events.len(), 1);
5824         match events[0] {
5825                 Event::PaymentSent { payment_preimage } => {
5826                         assert_eq!(payment_preimage, our_payment_preimage);
5827                 },
5828                 _ => panic!("Unexpected event"),
5829         }
5830
5831         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5832         check_added_monitors!(nodes[0], 1);
5833         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5834         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5835         check_added_monitors!(nodes[1], 1);
5836
5837         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5838         for i in 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + CHAN_CONFIRM_DEPTH + 1 {
5839                 nodes[1].block_notifier.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
5840                 header.prev_blockhash = header.block_hash();
5841         }
5842         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5843         check_closed_broadcast!(nodes[1], false);
5844         check_added_monitors!(nodes[1], 1);
5845 }
5846
5847 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5848         let chanmon_cfgs = create_chanmon_cfgs(2);
5849         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5850         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5851         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5852         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5853         let logger = test_utils::TestLogger::new();
5854
5855         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5856         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5857         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();
5858         nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
5859         check_added_monitors!(nodes[0], 1);
5860
5861         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5862
5863         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5864         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5865         // to "time out" the HTLC.
5866
5867         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5868
5869         for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5870                 nodes[0].block_notifier.block_connected(&Block { header, txdata: Vec::new()}, i);
5871                 header.prev_blockhash = header.block_hash();
5872         }
5873         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5874         check_closed_broadcast!(nodes[0], false);
5875         check_added_monitors!(nodes[0], 1);
5876 }
5877
5878 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5879         let chanmon_cfgs = create_chanmon_cfgs(3);
5880         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5881         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5882         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5883         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5884
5885         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5886         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5887         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5888         // actually revoked.
5889         let htlc_value = if use_dust { 50000 } else { 3000000 };
5890         let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5891         assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash, &None));
5892         expect_pending_htlcs_forwardable!(nodes[1]);
5893         check_added_monitors!(nodes[1], 1);
5894
5895         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5896         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5897         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5898         check_added_monitors!(nodes[0], 1);
5899         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5900         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5901         check_added_monitors!(nodes[1], 1);
5902         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5903         check_added_monitors!(nodes[1], 1);
5904         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5905
5906         if check_revoke_no_close {
5907                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5908                 check_added_monitors!(nodes[0], 1);
5909         }
5910
5911         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5912         for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5913                 nodes[0].block_notifier.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
5914                 header.prev_blockhash = header.block_hash();
5915         }
5916         if !check_revoke_no_close {
5917                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5918                 check_closed_broadcast!(nodes[0], false);
5919                 check_added_monitors!(nodes[0], 1);
5920         } else {
5921                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5922         }
5923 }
5924
5925 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5926 // There are only a few cases to test here:
5927 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5928 //    broadcastable commitment transactions result in channel closure,
5929 //  * its included in an unrevoked-but-previous remote commitment transaction,
5930 //  * its included in the latest remote or local commitment transactions.
5931 // We test each of the three possible commitment transactions individually and use both dust and
5932 // non-dust HTLCs.
5933 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5934 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5935 // tested for at least one of the cases in other tests.
5936 #[test]
5937 fn htlc_claim_single_commitment_only_a() {
5938         do_htlc_claim_local_commitment_only(true);
5939         do_htlc_claim_local_commitment_only(false);
5940
5941         do_htlc_claim_current_remote_commitment_only(true);
5942         do_htlc_claim_current_remote_commitment_only(false);
5943 }
5944
5945 #[test]
5946 fn htlc_claim_single_commitment_only_b() {
5947         do_htlc_claim_previous_remote_commitment_only(true, false);
5948         do_htlc_claim_previous_remote_commitment_only(false, false);
5949         do_htlc_claim_previous_remote_commitment_only(true, true);
5950         do_htlc_claim_previous_remote_commitment_only(false, true);
5951 }
5952
5953 #[test]
5954 #[should_panic]
5955 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5956         let chanmon_cfgs = create_chanmon_cfgs(2);
5957         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5958         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5959         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5960         //Force duplicate channel ids
5961         for node in nodes.iter() {
5962                 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5963         }
5964
5965         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5966         let channel_value_satoshis=10000;
5967         let push_msat=10001;
5968         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5969         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5970         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5971
5972         //Create a second channel with a channel_id collision
5973         assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5974 }
5975
5976 #[test]
5977 fn bolt2_open_channel_sending_node_checks_part2() {
5978         let chanmon_cfgs = create_chanmon_cfgs(2);
5979         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5980         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5981         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5982
5983         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5984         let channel_value_satoshis=2^24;
5985         let push_msat=10001;
5986         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5987
5988         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5989         let channel_value_satoshis=10000;
5990         // Test when push_msat is equal to 1000 * funding_satoshis.
5991         let push_msat=1000*channel_value_satoshis+1;
5992         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5993
5994         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5995         let channel_value_satoshis=10000;
5996         let push_msat=10001;
5997         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
5998         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5999         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
6000
6001         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
6002         // 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
6003         assert!(node0_to_1_send_open_channel.channel_flags<=1);
6004
6005         // 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.
6006         assert!(BREAKDOWN_TIMEOUT>0);
6007         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
6008
6009         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
6010         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
6011         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
6012
6013         // 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.
6014         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
6015         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
6016         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
6017         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
6018         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6019 }
6020
6021 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6022 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6023 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6024 // is no longer affordable once it's freed.
6025 #[test]
6026 fn test_fail_holding_cell_htlc_upon_free() {
6027         let chanmon_cfgs = create_chanmon_cfgs(2);
6028         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6029         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6030         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6031         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6032         let logger = test_utils::TestLogger::new();
6033
6034         // First nodes[0] generates an update_fee, setting the channel's
6035         // pending_update_fee.
6036         nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 20).unwrap();
6037         check_added_monitors!(nodes[0], 1);
6038
6039         let events = nodes[0].node.get_and_clear_pending_msg_events();
6040         assert_eq!(events.len(), 1);
6041         let (update_msg, commitment_signed) = match events[0] {
6042                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6043                         (update_fee.as_ref(), commitment_signed)
6044                 },
6045                 _ => panic!("Unexpected event"),
6046         };
6047
6048         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6049
6050         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6051         let channel_reserve = chan_stat.channel_reserve_msat;
6052         let feerate = get_feerate!(nodes[0], chan.2);
6053
6054         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6055         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6056         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1);
6057         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6058         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();
6059
6060         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6061         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6062         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6063         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6064
6065         // Flush the pending fee update.
6066         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6067         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6068         check_added_monitors!(nodes[1], 1);
6069         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6070         check_added_monitors!(nodes[0], 1);
6071
6072         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6073         // HTLC, but now that the fee has been raised the payment will now fail, causing
6074         // us to surface its failure to the user.
6075         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6076         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6077         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 1 HTLC updates".to_string(), 1);
6078         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);
6079         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6080
6081         // Check that the payment failed to be sent out.
6082         let events = nodes[0].node.get_and_clear_pending_events();
6083         assert_eq!(events.len(), 1);
6084         match &events[0] {
6085                 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6086                         assert_eq!(our_payment_hash.clone(), *payment_hash);
6087                         assert_eq!(*rejected_by_dest, false);
6088                         assert_eq!(*error_code, None);
6089                         assert_eq!(*error_data, None);
6090                 },
6091                 _ => panic!("Unexpected event"),
6092         }
6093 }
6094
6095 // Test that if multiple HTLCs are released from the holding cell and one is
6096 // valid but the other is no longer valid upon release, the valid HTLC can be
6097 // successfully completed while the other one fails as expected.
6098 #[test]
6099 fn test_free_and_fail_holding_cell_htlcs() {
6100         let chanmon_cfgs = create_chanmon_cfgs(2);
6101         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6102         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6103         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6104         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6105         let logger = test_utils::TestLogger::new();
6106
6107         // First nodes[0] generates an update_fee, setting the channel's
6108         // pending_update_fee.
6109         nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 200).unwrap();
6110         check_added_monitors!(nodes[0], 1);
6111
6112         let events = nodes[0].node.get_and_clear_pending_msg_events();
6113         assert_eq!(events.len(), 1);
6114         let (update_msg, commitment_signed) = match events[0] {
6115                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6116                         (update_fee.as_ref(), commitment_signed)
6117                 },
6118                 _ => panic!("Unexpected event"),
6119         };
6120
6121         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6122
6123         let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6124         let channel_reserve = chan_stat.channel_reserve_msat;
6125         let feerate = get_feerate!(nodes[0], chan.2);
6126
6127         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6128         let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
6129         let amt_1 = 20000;
6130         let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
6131         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1) - amt_1;
6132         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6133         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();
6134         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();
6135
6136         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6137         nodes[0].node.send_payment(&route_1, payment_hash_1, &None).unwrap();
6138         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6139         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6140         nodes[0].node.send_payment(&route_2, payment_hash_2, &None).unwrap();
6141         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6142         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6143
6144         // Flush the pending fee update.
6145         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6146         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6147         check_added_monitors!(nodes[1], 1);
6148         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6149         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6150         check_added_monitors!(nodes[0], 2);
6151
6152         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6153         // but now that the fee has been raised the second payment will now fail, causing us
6154         // to surface its failure to the user. The first payment should succeed.
6155         chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6156         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6157         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 2 HTLC updates".to_string(), 1);
6158         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);
6159         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6160
6161         // Check that the second payment failed to be sent out.
6162         let events = nodes[0].node.get_and_clear_pending_events();
6163         assert_eq!(events.len(), 1);
6164         match &events[0] {
6165                 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6166                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6167                         assert_eq!(*rejected_by_dest, false);
6168                         assert_eq!(*error_code, None);
6169                         assert_eq!(*error_data, None);
6170                 },
6171                 _ => panic!("Unexpected event"),
6172         }
6173
6174         // Complete the first payment and the RAA from the fee update.
6175         let (payment_event, send_raa_event) = {
6176                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6177                 assert_eq!(msgs.len(), 2);
6178                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6179         };
6180         let raa = match send_raa_event {
6181                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6182                 _ => panic!("Unexpected event"),
6183         };
6184         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6185         check_added_monitors!(nodes[1], 1);
6186         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6187         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6188         let events = nodes[1].node.get_and_clear_pending_events();
6189         assert_eq!(events.len(), 1);
6190         match events[0] {
6191                 Event::PendingHTLCsForwardable { .. } => {},
6192                 _ => panic!("Unexpected event"),
6193         }
6194         nodes[1].node.process_pending_htlc_forwards();
6195         let events = nodes[1].node.get_and_clear_pending_events();
6196         assert_eq!(events.len(), 1);
6197         match events[0] {
6198                 Event::PaymentReceived { .. } => {},
6199                 _ => panic!("Unexpected event"),
6200         }
6201         nodes[1].node.claim_funds(payment_preimage_1, &None, amt_1);
6202         check_added_monitors!(nodes[1], 1);
6203         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6204         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6205         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6206         let events = nodes[0].node.get_and_clear_pending_events();
6207         assert_eq!(events.len(), 1);
6208         match events[0] {
6209                 Event::PaymentSent { ref payment_preimage } => {
6210                         assert_eq!(*payment_preimage, payment_preimage_1);
6211                 }
6212                 _ => panic!("Unexpected event"),
6213         }
6214 }
6215
6216 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6217 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6218 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6219 // once it's freed.
6220 #[test]
6221 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6222         let chanmon_cfgs = create_chanmon_cfgs(3);
6223         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6224         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6225         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6226         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6227         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6228         let logger = test_utils::TestLogger::new();
6229
6230         // First nodes[1] generates an update_fee, setting the channel's
6231         // pending_update_fee.
6232         nodes[1].node.update_fee(chan_1_2.2, get_feerate!(nodes[1], chan_1_2.2) + 20).unwrap();
6233         check_added_monitors!(nodes[1], 1);
6234
6235         let events = nodes[1].node.get_and_clear_pending_msg_events();
6236         assert_eq!(events.len(), 1);
6237         let (update_msg, commitment_signed) = match events[0] {
6238                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6239                         (update_fee.as_ref(), commitment_signed)
6240                 },
6241                 _ => panic!("Unexpected event"),
6242         };
6243
6244         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6245
6246         let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6247         let channel_reserve = chan_stat.channel_reserve_msat;
6248         let feerate = get_feerate!(nodes[0], chan_0_1.2);
6249
6250         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6251         let feemsat = 239;
6252         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6253         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6254         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1) - total_routing_fee_msat;
6255         let payment_event = {
6256                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6257                 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();
6258                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6259                 check_added_monitors!(nodes[0], 1);
6260
6261                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6262                 assert_eq!(events.len(), 1);
6263
6264                 SendEvent::from_event(events.remove(0))
6265         };
6266         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6267         check_added_monitors!(nodes[1], 0);
6268         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6269         expect_pending_htlcs_forwardable!(nodes[1]);
6270
6271         chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6272         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6273
6274         // Flush the pending fee update.
6275         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6276         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6277         check_added_monitors!(nodes[2], 1);
6278         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6279         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6280         check_added_monitors!(nodes[1], 2);
6281
6282         // A final RAA message is generated to finalize the fee update.
6283         let events = nodes[1].node.get_and_clear_pending_msg_events();
6284         assert_eq!(events.len(), 1);
6285
6286         let raa_msg = match &events[0] {
6287                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6288                         msg.clone()
6289                 },
6290                 _ => panic!("Unexpected event"),
6291         };
6292
6293         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6294         check_added_monitors!(nodes[2], 1);
6295         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6296
6297         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6298         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6299         assert_eq!(process_htlc_forwards_event.len(), 1);
6300         match &process_htlc_forwards_event[0] {
6301                 &Event::PendingHTLCsForwardable { .. } => {},
6302                 _ => panic!("Unexpected event"),
6303         }
6304
6305         // In response, we call ChannelManager's process_pending_htlc_forwards
6306         nodes[1].node.process_pending_htlc_forwards();
6307         check_added_monitors!(nodes[1], 1);
6308
6309         // This causes the HTLC to be failed backwards.
6310         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6311         assert_eq!(fail_event.len(), 1);
6312         let (fail_msg, commitment_signed) = match &fail_event[0] {
6313                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6314                         assert_eq!(updates.update_add_htlcs.len(), 0);
6315                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6316                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6317                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6318                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6319                 },
6320                 _ => panic!("Unexpected event"),
6321         };
6322
6323         // Pass the failure messages back to nodes[0].
6324         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6325         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6326
6327         // Complete the HTLC failure+removal process.
6328         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6329         check_added_monitors!(nodes[0], 1);
6330         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6331         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6332         check_added_monitors!(nodes[1], 2);
6333         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6334         assert_eq!(final_raa_event.len(), 1);
6335         let raa = match &final_raa_event[0] {
6336                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6337                 _ => panic!("Unexpected event"),
6338         };
6339         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6340         let fail_msg_event = nodes[0].node.get_and_clear_pending_msg_events();
6341         assert_eq!(fail_msg_event.len(), 1);
6342         match &fail_msg_event[0] {
6343                 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6344                 _ => panic!("Unexpected event"),
6345         }
6346         let failure_event = nodes[0].node.get_and_clear_pending_events();
6347         assert_eq!(failure_event.len(), 1);
6348         match &failure_event[0] {
6349                 &Event::PaymentFailed { rejected_by_dest, .. } => {
6350                         assert!(!rejected_by_dest);
6351                 },
6352                 _ => panic!("Unexpected event"),
6353         }
6354         check_added_monitors!(nodes[0], 1);
6355 }
6356
6357 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6358 // 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.
6359 //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.
6360
6361 #[test]
6362 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6363         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6364         let chanmon_cfgs = create_chanmon_cfgs(2);
6365         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6366         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6367         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6368         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6369
6370         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6371         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6372         let logger = test_utils::TestLogger::new();
6373         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();
6374         route.paths[0][0].fee_msat = 100;
6375
6376         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6377                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6378         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6379         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6380 }
6381
6382 #[test]
6383 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6384         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6385         let chanmon_cfgs = create_chanmon_cfgs(2);
6386         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6387         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6388         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6389         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6390         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6391
6392         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6393         let logger = test_utils::TestLogger::new();
6394         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();
6395         route.paths[0][0].fee_msat = 0;
6396         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6397                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6398
6399         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6400         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6401 }
6402
6403 #[test]
6404 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6405         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
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 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         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6417         check_added_monitors!(nodes[0], 1);
6418         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6419         updates.update_add_htlcs[0].amount_msat = 0;
6420
6421         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6422         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6423         check_closed_broadcast!(nodes[1], true).unwrap();
6424         check_added_monitors!(nodes[1], 1);
6425 }
6426
6427 #[test]
6428 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6429         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6430         //It is enforced when constructing a route.
6431         let chanmon_cfgs = create_chanmon_cfgs(2);
6432         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6433         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6434         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6435         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 0, InitFeatures::known(), InitFeatures::known());
6436         let logger = test_utils::TestLogger::new();
6437
6438         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6439
6440         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6441         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();
6442         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::RouteError { ref err },
6443                 assert_eq!(err, &"Channel CLTV overflowed?"));
6444 }
6445
6446 #[test]
6447 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6448         //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.
6449         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6450         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6451         let chanmon_cfgs = create_chanmon_cfgs(2);
6452         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6453         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6454         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6455         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6456         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6457
6458         let logger = test_utils::TestLogger::new();
6459         for i in 0..max_accepted_htlcs {
6460                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6461                 let payment_event = {
6462                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6463                         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();
6464                         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6465                         check_added_monitors!(nodes[0], 1);
6466
6467                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6468                         assert_eq!(events.len(), 1);
6469                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6470                                 assert_eq!(htlcs[0].htlc_id, i);
6471                         } else {
6472                                 assert!(false);
6473                         }
6474                         SendEvent::from_event(events.remove(0))
6475                 };
6476                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6477                 check_added_monitors!(nodes[1], 0);
6478                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6479
6480                 expect_pending_htlcs_forwardable!(nodes[1]);
6481                 expect_payment_received!(nodes[1], our_payment_hash, 100000);
6482         }
6483         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6484         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6485         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();
6486         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6487                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6488
6489         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6490         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6491 }
6492
6493 #[test]
6494 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6495         //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.
6496         let chanmon_cfgs = create_chanmon_cfgs(2);
6497         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6498         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6499         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6500         let channel_value = 100000;
6501         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6502         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6503
6504         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight, max_in_flight);
6505
6506         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6507         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6508         let logger = test_utils::TestLogger::new();
6509         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &[], max_in_flight+1, TEST_FINAL_CLTV, &logger).unwrap();
6510         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6511                 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)));
6512
6513         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6514         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);
6515
6516         send_payment(&nodes[0], &[&nodes[1]], max_in_flight, max_in_flight);
6517 }
6518
6519 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6520 #[test]
6521 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6522         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6523         let chanmon_cfgs = create_chanmon_cfgs(2);
6524         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6525         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6526         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6527         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6528         let htlc_minimum_msat: u64;
6529         {
6530                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6531                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6532                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6533         }
6534
6535         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6536         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6537         let logger = test_utils::TestLogger::new();
6538         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();
6539         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6540         check_added_monitors!(nodes[0], 1);
6541         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6542         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6543         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6544         assert!(nodes[1].node.list_channels().is_empty());
6545         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6546         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()));
6547         check_added_monitors!(nodes[1], 1);
6548 }
6549
6550 #[test]
6551 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6552         //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
6553         let chanmon_cfgs = create_chanmon_cfgs(2);
6554         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6555         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6556         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6557         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6558         let logger = test_utils::TestLogger::new();
6559
6560         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6561         let channel_reserve = chan_stat.channel_reserve_msat;
6562         let feerate = get_feerate!(nodes[0], chan.2);
6563         // The 2* and +1 are for the fee spike reserve.
6564         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1);
6565
6566         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6567         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6568         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6569         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();
6570         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6571         check_added_monitors!(nodes[0], 1);
6572         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6573
6574         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6575         // at this time channel-initiatee receivers are not required to enforce that senders
6576         // respect the fee_spike_reserve.
6577         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6578         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6579
6580         assert!(nodes[1].node.list_channels().is_empty());
6581         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6582         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6583         check_added_monitors!(nodes[1], 1);
6584 }
6585
6586 #[test]
6587 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6588         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6589         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6590         let chanmon_cfgs = create_chanmon_cfgs(2);
6591         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6592         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6593         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6594         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6595         let logger = test_utils::TestLogger::new();
6596
6597         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6598         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6599
6600         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6601         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();
6602
6603         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
6604         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6605         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &None, cur_height).unwrap();
6606         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6607
6608         let mut msg = msgs::UpdateAddHTLC {
6609                 channel_id: chan.2,
6610                 htlc_id: 0,
6611                 amount_msat: 1000,
6612                 payment_hash: our_payment_hash,
6613                 cltv_expiry: htlc_cltv,
6614                 onion_routing_packet: onion_packet.clone(),
6615         };
6616
6617         for i in 0..super::channel::OUR_MAX_HTLCS {
6618                 msg.htlc_id = i as u64;
6619                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6620         }
6621         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6622         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6623
6624         assert!(nodes[1].node.list_channels().is_empty());
6625         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6626         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6627         check_added_monitors!(nodes[1], 1);
6628 }
6629
6630 #[test]
6631 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6632         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6633         let chanmon_cfgs = create_chanmon_cfgs(2);
6634         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6635         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6636         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6637         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6638         let logger = test_utils::TestLogger::new();
6639
6640         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6641         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6642         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();
6643         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6644         check_added_monitors!(nodes[0], 1);
6645         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6646         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6647         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6648
6649         assert!(nodes[1].node.list_channels().is_empty());
6650         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6651         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6652         check_added_monitors!(nodes[1], 1);
6653 }
6654
6655 #[test]
6656 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6657         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6658         let chanmon_cfgs = create_chanmon_cfgs(2);
6659         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6660         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6661         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6662         let logger = test_utils::TestLogger::new();
6663
6664         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6665         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6666         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6667         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();
6668         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6669         check_added_monitors!(nodes[0], 1);
6670         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6671         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6672         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6673
6674         assert!(nodes[1].node.list_channels().is_empty());
6675         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6676         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6677         check_added_monitors!(nodes[1], 1);
6678 }
6679
6680 #[test]
6681 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6682         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6683         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6684         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6685         let chanmon_cfgs = create_chanmon_cfgs(2);
6686         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6687         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6688         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6689         let logger = test_utils::TestLogger::new();
6690
6691         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6692         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6693         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6694         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();
6695         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6696         check_added_monitors!(nodes[0], 1);
6697         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6698         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6699
6700         //Disconnect and Reconnect
6701         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6702         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6703         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6704         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6705         assert_eq!(reestablish_1.len(), 1);
6706         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6707         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6708         assert_eq!(reestablish_2.len(), 1);
6709         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6710         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6711         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6712         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6713
6714         //Resend HTLC
6715         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6716         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6717         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6718         check_added_monitors!(nodes[1], 1);
6719         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6720
6721         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6722
6723         assert!(nodes[1].node.list_channels().is_empty());
6724         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6725         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6726         check_added_monitors!(nodes[1], 1);
6727 }
6728
6729 #[test]
6730 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6731         //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.
6732
6733         let chanmon_cfgs = create_chanmon_cfgs(2);
6734         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6735         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6736         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6737         let logger = test_utils::TestLogger::new();
6738         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6739         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6740         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6741         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();
6742         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6743
6744         check_added_monitors!(nodes[0], 1);
6745         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6746         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6747
6748         let update_msg = msgs::UpdateFulfillHTLC{
6749                 channel_id: chan.2,
6750                 htlc_id: 0,
6751                 payment_preimage: our_payment_preimage,
6752         };
6753
6754         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6755
6756         assert!(nodes[0].node.list_channels().is_empty());
6757         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6758         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()));
6759         check_added_monitors!(nodes[0], 1);
6760 }
6761
6762 #[test]
6763 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6764         //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.
6765
6766         let chanmon_cfgs = create_chanmon_cfgs(2);
6767         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6768         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6769         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6770         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6771         let logger = test_utils::TestLogger::new();
6772
6773         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6774         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6775         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();
6776         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6777         check_added_monitors!(nodes[0], 1);
6778         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6779         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6780
6781         let update_msg = msgs::UpdateFailHTLC{
6782                 channel_id: chan.2,
6783                 htlc_id: 0,
6784                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6785         };
6786
6787         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6788
6789         assert!(nodes[0].node.list_channels().is_empty());
6790         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6791         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()));
6792         check_added_monitors!(nodes[0], 1);
6793 }
6794
6795 #[test]
6796 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6797         //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.
6798
6799         let chanmon_cfgs = create_chanmon_cfgs(2);
6800         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6801         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6802         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6803         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6804         let logger = test_utils::TestLogger::new();
6805
6806         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6807         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6808         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();
6809         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6810         check_added_monitors!(nodes[0], 1);
6811         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6812         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6813
6814         let update_msg = msgs::UpdateFailMalformedHTLC{
6815                 channel_id: chan.2,
6816                 htlc_id: 0,
6817                 sha256_of_onion: [1; 32],
6818                 failure_code: 0x8000,
6819         };
6820
6821         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6822
6823         assert!(nodes[0].node.list_channels().is_empty());
6824         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6825         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()));
6826         check_added_monitors!(nodes[0], 1);
6827 }
6828
6829 #[test]
6830 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6831         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6832
6833         let chanmon_cfgs = create_chanmon_cfgs(2);
6834         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6835         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6836         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6837         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6838
6839         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6840
6841         nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6842         check_added_monitors!(nodes[1], 1);
6843
6844         let events = nodes[1].node.get_and_clear_pending_msg_events();
6845         assert_eq!(events.len(), 1);
6846         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6847                 match events[0] {
6848                         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, .. } } => {
6849                                 assert!(update_add_htlcs.is_empty());
6850                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6851                                 assert!(update_fail_htlcs.is_empty());
6852                                 assert!(update_fail_malformed_htlcs.is_empty());
6853                                 assert!(update_fee.is_none());
6854                                 update_fulfill_htlcs[0].clone()
6855                         },
6856                         _ => panic!("Unexpected event"),
6857                 }
6858         };
6859
6860         update_fulfill_msg.htlc_id = 1;
6861
6862         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6863
6864         assert!(nodes[0].node.list_channels().is_empty());
6865         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6866         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6867         check_added_monitors!(nodes[0], 1);
6868 }
6869
6870 #[test]
6871 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6872         //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.
6873
6874         let chanmon_cfgs = create_chanmon_cfgs(2);
6875         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6876         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6877         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6878         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6879
6880         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6881
6882         nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6883         check_added_monitors!(nodes[1], 1);
6884
6885         let events = nodes[1].node.get_and_clear_pending_msg_events();
6886         assert_eq!(events.len(), 1);
6887         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6888                 match events[0] {
6889                         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, .. } } => {
6890                                 assert!(update_add_htlcs.is_empty());
6891                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6892                                 assert!(update_fail_htlcs.is_empty());
6893                                 assert!(update_fail_malformed_htlcs.is_empty());
6894                                 assert!(update_fee.is_none());
6895                                 update_fulfill_htlcs[0].clone()
6896                         },
6897                         _ => panic!("Unexpected event"),
6898                 }
6899         };
6900
6901         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6902
6903         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6904
6905         assert!(nodes[0].node.list_channels().is_empty());
6906         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6907         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6908         check_added_monitors!(nodes[0], 1);
6909 }
6910
6911 #[test]
6912 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6913         //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.
6914
6915         let chanmon_cfgs = create_chanmon_cfgs(2);
6916         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6917         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6918         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6919         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6920         let logger = test_utils::TestLogger::new();
6921
6922         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6923         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6924         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();
6925         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6926         check_added_monitors!(nodes[0], 1);
6927
6928         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6929         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6930
6931         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6932         check_added_monitors!(nodes[1], 0);
6933         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6934
6935         let events = nodes[1].node.get_and_clear_pending_msg_events();
6936
6937         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6938                 match events[0] {
6939                         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, .. } } => {
6940                                 assert!(update_add_htlcs.is_empty());
6941                                 assert!(update_fulfill_htlcs.is_empty());
6942                                 assert!(update_fail_htlcs.is_empty());
6943                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6944                                 assert!(update_fee.is_none());
6945                                 update_fail_malformed_htlcs[0].clone()
6946                         },
6947                         _ => panic!("Unexpected event"),
6948                 }
6949         };
6950         update_msg.failure_code &= !0x8000;
6951         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6952
6953         assert!(nodes[0].node.list_channels().is_empty());
6954         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6955         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6956         check_added_monitors!(nodes[0], 1);
6957 }
6958
6959 #[test]
6960 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6961         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6962         //    * 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.
6963
6964         let chanmon_cfgs = create_chanmon_cfgs(3);
6965         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6966         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6967         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6968         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6969         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6970         let logger = test_utils::TestLogger::new();
6971
6972         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6973
6974         //First hop
6975         let mut payment_event = {
6976                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6977                 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();
6978                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6979                 check_added_monitors!(nodes[0], 1);
6980                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6981                 assert_eq!(events.len(), 1);
6982                 SendEvent::from_event(events.remove(0))
6983         };
6984         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6985         check_added_monitors!(nodes[1], 0);
6986         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6987         expect_pending_htlcs_forwardable!(nodes[1]);
6988         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6989         assert_eq!(events_2.len(), 1);
6990         check_added_monitors!(nodes[1], 1);
6991         payment_event = SendEvent::from_event(events_2.remove(0));
6992         assert_eq!(payment_event.msgs.len(), 1);
6993
6994         //Second Hop
6995         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6996         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6997         check_added_monitors!(nodes[2], 0);
6998         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6999
7000         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7001         assert_eq!(events_3.len(), 1);
7002         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
7003                 match events_3[0] {
7004                         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 } } => {
7005                                 assert!(update_add_htlcs.is_empty());
7006                                 assert!(update_fulfill_htlcs.is_empty());
7007                                 assert!(update_fail_htlcs.is_empty());
7008                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7009                                 assert!(update_fee.is_none());
7010                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
7011                         },
7012                         _ => panic!("Unexpected event"),
7013                 }
7014         };
7015
7016         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
7017
7018         check_added_monitors!(nodes[1], 0);
7019         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
7020         expect_pending_htlcs_forwardable!(nodes[1]);
7021         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7022         assert_eq!(events_4.len(), 1);
7023
7024         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7025         match events_4[0] {
7026                 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, .. } } => {
7027                         assert!(update_add_htlcs.is_empty());
7028                         assert!(update_fulfill_htlcs.is_empty());
7029                         assert_eq!(update_fail_htlcs.len(), 1);
7030                         assert!(update_fail_malformed_htlcs.is_empty());
7031                         assert!(update_fee.is_none());
7032                 },
7033                 _ => panic!("Unexpected event"),
7034         };
7035
7036         check_added_monitors!(nodes[1], 1);
7037 }
7038
7039 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7040         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7041         // 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
7042         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7043
7044         let chanmon_cfgs = create_chanmon_cfgs(2);
7045         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7046         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7047         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7048         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7049
7050         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7051
7052         // We route 2 dust-HTLCs between A and B
7053         let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7054         let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7055         route_payment(&nodes[0], &[&nodes[1]], 1000000);
7056
7057         // Cache one local commitment tx as previous
7058         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7059
7060         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7061         assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2, &None));
7062         check_added_monitors!(nodes[1], 0);
7063         expect_pending_htlcs_forwardable!(nodes[1]);
7064         check_added_monitors!(nodes[1], 1);
7065
7066         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7067         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7068         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7069         check_added_monitors!(nodes[0], 1);
7070
7071         // Cache one local commitment tx as lastest
7072         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7073
7074         let events = nodes[0].node.get_and_clear_pending_msg_events();
7075         match events[0] {
7076                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7077                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7078                 },
7079                 _ => panic!("Unexpected event"),
7080         }
7081         match events[1] {
7082                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7083                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7084                 },
7085                 _ => panic!("Unexpected event"),
7086         }
7087
7088         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7089         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7090         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7091
7092         if announce_latest {
7093                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_last_commitment_tx[0].clone()]}, 1);
7094         } else {
7095                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_prev_commitment_tx[0].clone()]}, 1);
7096         }
7097
7098         check_closed_broadcast!(nodes[0], false);
7099         check_added_monitors!(nodes[0], 1);
7100
7101         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7102         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 1, true,  header.block_hash());
7103         let events = nodes[0].node.get_and_clear_pending_events();
7104         // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
7105         assert_eq!(events.len(), 2);
7106         let mut first_failed = false;
7107         for event in events {
7108                 match event {
7109                         Event::PaymentFailed { payment_hash, .. } => {
7110                                 if payment_hash == payment_hash_1 {
7111                                         assert!(!first_failed);
7112                                         first_failed = true;
7113                                 } else {
7114                                         assert_eq!(payment_hash, payment_hash_2);
7115                                 }
7116                         }
7117                         _ => panic!("Unexpected event"),
7118                 }
7119         }
7120 }
7121
7122 #[test]
7123 fn test_failure_delay_dust_htlc_local_commitment() {
7124         do_test_failure_delay_dust_htlc_local_commitment(true);
7125         do_test_failure_delay_dust_htlc_local_commitment(false);
7126 }
7127
7128 #[test]
7129 fn test_no_failure_dust_htlc_local_commitment() {
7130         // Transaction filters for failing back dust htlc based on local commitment txn infos has been
7131         // prone to error, we test here that a dummy transaction don't fail them.
7132
7133         let chanmon_cfgs = create_chanmon_cfgs(2);
7134         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7135         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7136         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7137         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7138
7139         // Rebalance a bit
7140         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7141
7142         let as_dust_limit = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7143         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7144
7145         // We route 2 dust-HTLCs between A and B
7146         let (preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7147         let (preimage_2, _) = route_payment(&nodes[1], &[&nodes[0]], as_dust_limit*1000);
7148
7149         // Build a dummy invalid transaction trying to spend a commitment tx
7150         let input = TxIn {
7151                 previous_output: BitcoinOutPoint { txid: chan.3.txid(), vout: 0 },
7152                 script_sig: Script::new(),
7153                 sequence: 0,
7154                 witness: Vec::new(),
7155         };
7156
7157         let outp = TxOut {
7158                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
7159                 value: 10000,
7160         };
7161
7162         let dummy_tx = Transaction {
7163                 version: 2,
7164                 lock_time: 0,
7165                 input: vec![input],
7166                 output: vec![outp]
7167         };
7168
7169         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7170         nodes[0].chan_monitor.simple_monitor.block_connected(&header, 1, &[&dummy_tx], &[1;1]);
7171         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7172         assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
7173         // We broadcast a few more block to check everything is all right
7174         connect_blocks(&nodes[0].block_notifier, 20, 1, true,  header.block_hash());
7175         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7176         assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
7177
7178         claim_payment(&nodes[0], &vec!(&nodes[1])[..], preimage_1, bs_dust_limit*1000);
7179         claim_payment(&nodes[1], &vec!(&nodes[0])[..], preimage_2, as_dust_limit*1000);
7180 }
7181
7182 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7183         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7184         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7185         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7186         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7187         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7188         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7189
7190         let chanmon_cfgs = create_chanmon_cfgs(3);
7191         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7192         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7193         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7194         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7195
7196         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7197
7198         let (_payment_preimage_1, dust_hash) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7199         let (_payment_preimage_2, non_dust_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7200
7201         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7202         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7203
7204         // We revoked bs_commitment_tx
7205         if revoked {
7206                 let (payment_preimage_3, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7207                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 1_000_000);
7208         }
7209
7210         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7211         let mut timeout_tx = Vec::new();
7212         if local {
7213                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7214                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_commitment_tx[0].clone()]}, 1);
7215                 check_closed_broadcast!(nodes[0], false);
7216                 check_added_monitors!(nodes[0], 1);
7217                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7218                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7219                 let parent_hash  = connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 2, true, header.block_hash());
7220                 expect_payment_failed!(nodes[0], dust_hash, true);
7221                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7222                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7223                 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7224                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7225                 nodes[0].block_notifier.block_connected(&Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
7226                 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7227                 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 8, true, header_3.block_hash());
7228                 expect_payment_failed!(nodes[0], non_dust_hash, true);
7229         } else {
7230                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7231                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![bs_commitment_tx[0].clone()]}, 1);
7232                 check_closed_broadcast!(nodes[0], false);
7233                 check_added_monitors!(nodes[0], 1);
7234                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7235                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7236                 let parent_hash  = connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 2, true, header.block_hash());
7237                 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7238                 if !revoked {
7239                         expect_payment_failed!(nodes[0], dust_hash, true);
7240                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7241                         // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7242                         nodes[0].block_notifier.block_connected(&Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
7243                         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7244                         let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7245                         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 8, true, header_3.block_hash());
7246                         expect_payment_failed!(nodes[0], non_dust_hash, true);
7247                 } else {
7248                         // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7249                         // commitment tx
7250                         let events = nodes[0].node.get_and_clear_pending_events();
7251                         assert_eq!(events.len(), 2);
7252                         let first;
7253                         match events[0] {
7254                                 Event::PaymentFailed { payment_hash, .. } => {
7255                                         if payment_hash == dust_hash { first = true; }
7256                                         else { first = false; }
7257                                 },
7258                                 _ => panic!("Unexpected event"),
7259                         }
7260                         match events[1] {
7261                                 Event::PaymentFailed { payment_hash, .. } => {
7262                                         if first { assert_eq!(payment_hash, non_dust_hash); }
7263                                         else { assert_eq!(payment_hash, dust_hash); }
7264                                 },
7265                                 _ => panic!("Unexpected event"),
7266                         }
7267                 }
7268         }
7269 }
7270
7271 #[test]
7272 fn test_sweep_outbound_htlc_failure_update() {
7273         do_test_sweep_outbound_htlc_failure_update(false, true);
7274         do_test_sweep_outbound_htlc_failure_update(false, false);
7275         do_test_sweep_outbound_htlc_failure_update(true, false);
7276 }
7277
7278 #[test]
7279 fn test_upfront_shutdown_script() {
7280         // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
7281         // enforce it at shutdown message
7282
7283         let mut config = UserConfig::default();
7284         config.channel_options.announced_channel = true;
7285         config.peer_channel_config_limits.force_announced_channel_preference = false;
7286         config.channel_options.commit_upfront_shutdown_pubkey = false;
7287         let user_cfgs = [None, Some(config), None];
7288         let chanmon_cfgs = create_chanmon_cfgs(3);
7289         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7290         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7291         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7292
7293         // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
7294         let flags = InitFeatures::known();
7295         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7296         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7297         let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7298         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7299         // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that  we disconnect peer
7300         nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
7301     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()));
7302         check_added_monitors!(nodes[2], 1);
7303
7304         // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
7305         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7306         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7307         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7308         // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
7309         nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
7310         let events = nodes[2].node.get_and_clear_pending_msg_events();
7311         assert_eq!(events.len(), 1);
7312         match events[0] {
7313                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7314                 _ => panic!("Unexpected event"),
7315         }
7316
7317         // We test that if case of peer non-signaling we don't enforce committed script at channel opening
7318         let flags_no = InitFeatures::known().clear_upfront_shutdown_script();
7319         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone());
7320         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7321         let mut node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
7322         node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7323         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_1_shutdown);
7324         let events = nodes[1].node.get_and_clear_pending_msg_events();
7325         assert_eq!(events.len(), 1);
7326         match events[0] {
7327                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7328                 _ => panic!("Unexpected event"),
7329         }
7330
7331         // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7332         // channel smoothly, opt-out is from channel initiator here
7333         let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone());
7334         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7335         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7336         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7337         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
7338         let events = nodes[0].node.get_and_clear_pending_msg_events();
7339         assert_eq!(events.len(), 1);
7340         match events[0] {
7341                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7342                 _ => panic!("Unexpected event"),
7343         }
7344
7345         //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7346         //// channel smoothly
7347         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone());
7348         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7349         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7350         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7351         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
7352         let events = nodes[0].node.get_and_clear_pending_msg_events();
7353         assert_eq!(events.len(), 2);
7354         match events[0] {
7355                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7356                 _ => panic!("Unexpected event"),
7357         }
7358         match events[1] {
7359                 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7360                 _ => panic!("Unexpected event"),
7361         }
7362 }
7363
7364 #[test]
7365 fn test_user_configurable_csv_delay() {
7366         // We test our channel constructors yield errors when we pass them absurd csv delay
7367
7368         let mut low_our_to_self_config = UserConfig::default();
7369         low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7370         let mut high_their_to_self_config = UserConfig::default();
7371         high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7372         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7373         let chanmon_cfgs = create_chanmon_cfgs(2);
7374         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7375         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7376         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7377
7378         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7379         let keys_manager: Arc<KeysInterface<ChanKeySigner = EnforcingChannelKeys>> = Arc::new(test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet));
7380         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) {
7381                 match error {
7382                         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())); },
7383                         _ => panic!("Unexpected event"),
7384                 }
7385         } else { assert!(false) }
7386
7387         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7388         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7389         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7390         open_channel.to_self_delay = 200;
7391         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) {
7392                 match error {
7393                         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()));  },
7394                         _ => panic!("Unexpected event"),
7395                 }
7396         } else { assert!(false); }
7397
7398         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7399         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7400         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()));
7401         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7402         accept_channel.to_self_delay = 200;
7403         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7404         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7405                 match action {
7406                         &ErrorAction::SendErrorMessage { ref msg } => {
7407                                 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()));
7408                         },
7409                         _ => { assert!(false); }
7410                 }
7411         } else { assert!(false); }
7412
7413         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7414         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7415         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7416         open_channel.to_self_delay = 200;
7417         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) {
7418                 match error {
7419                         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())); },
7420                         _ => panic!("Unexpected event"),
7421                 }
7422         } else { assert!(false); }
7423 }
7424
7425 #[test]
7426 fn test_data_loss_protect() {
7427         // We want to be sure that :
7428         // * we don't broadcast our Local Commitment Tx in case of fallen behind
7429         // * we close channel in case of detecting other being fallen behind
7430         // * we are able to claim our own outputs thanks to to_remote being static
7431         let keys_manager;
7432         let logger;
7433         let fee_estimator;
7434         let tx_broadcaster;
7435         let chain_monitor;
7436         let monitor;
7437         let node_state_0;
7438         let chanmon_cfgs = create_chanmon_cfgs(2);
7439         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7440         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7441         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7442
7443         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7444
7445         // Cache node A state before any channel update
7446         let previous_node_state = nodes[0].node.encode();
7447         let mut previous_chan_monitor_state = test_utils::TestVecWriter(Vec::new());
7448         nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut previous_chan_monitor_state).unwrap();
7449
7450         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7451         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7452
7453         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7454         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7455
7456         // Restore node A from previous state
7457         logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7458         let mut chan_monitor = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut ::std::io::Cursor::new(previous_chan_monitor_state.0)).unwrap().1;
7459         chain_monitor = ChainWatchInterfaceUtil::new(Network::Testnet);
7460         tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
7461         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
7462         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
7463         monitor = test_utils::TestChannelMonitor::new(&chain_monitor, &tx_broadcaster, &logger, &fee_estimator);
7464         node_state_0 = {
7465                 let mut channel_monitors = HashMap::new();
7466                 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chan_monitor);
7467                 <(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 {
7468                         keys_manager: &keys_manager,
7469                         fee_estimator: &fee_estimator,
7470                         monitor: &monitor,
7471                         logger: &logger,
7472                         tx_broadcaster: &tx_broadcaster,
7473                         default_config: UserConfig::default(),
7474                         channel_monitors,
7475                 }).unwrap().1
7476         };
7477         nodes[0].node = &node_state_0;
7478         assert!(monitor.add_monitor(OutPoint { txid: chan.3.txid(), index: 0 }, chan_monitor).is_ok());
7479         nodes[0].chan_monitor = &monitor;
7480         nodes[0].chain_monitor = &chain_monitor;
7481
7482         nodes[0].block_notifier = BlockNotifier::new(&nodes[0].chain_monitor);
7483         nodes[0].block_notifier.register_listener(&nodes[0].chan_monitor.simple_monitor);
7484         nodes[0].block_notifier.register_listener(nodes[0].node);
7485
7486         check_added_monitors!(nodes[0], 1);
7487
7488         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7489         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7490
7491         let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7492
7493         // Check we don't broadcast any transactions following learning of per_commitment_point from B
7494         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7495         check_added_monitors!(nodes[0], 1);
7496
7497         {
7498                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7499                 assert_eq!(node_txn.len(), 0);
7500         }
7501
7502         let mut reestablish_1 = Vec::with_capacity(1);
7503         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7504                 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7505                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7506                         reestablish_1.push(msg.clone());
7507                 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7508                 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7509                         match action {
7510                                 &ErrorAction::SendErrorMessage { ref msg } => {
7511                                         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");
7512                                 },
7513                                 _ => panic!("Unexpected event!"),
7514                         }
7515                 } else {
7516                         panic!("Unexpected event")
7517                 }
7518         }
7519
7520         // Check we close channel detecting A is fallen-behind
7521         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7522         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7523         check_added_monitors!(nodes[1], 1);
7524
7525
7526         // Check A is able to claim to_remote output
7527         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7528         assert_eq!(node_txn.len(), 1);
7529         check_spends!(node_txn[0], chan.3);
7530         assert_eq!(node_txn[0].output.len(), 2);
7531         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
7532         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()]}, 0);
7533         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
7534         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
7535         assert_eq!(spend_txn.len(), 1);
7536         check_spends!(spend_txn[0], node_txn[0]);
7537 }
7538
7539 #[test]
7540 fn test_check_htlc_underpaying() {
7541         // Send payment through A -> B but A is maliciously
7542         // sending a probe payment (i.e less than expected value0
7543         // to B, B should refuse payment.
7544
7545         let chanmon_cfgs = create_chanmon_cfgs(2);
7546         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7547         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7548         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7549
7550         // Create some initial channels
7551         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7552
7553         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 10_000);
7554
7555         // Node 3 is expecting payment of 100_000 but receive 10_000,
7556         // fail htlc like we didn't know the preimage.
7557         nodes[1].node.claim_funds(payment_preimage, &None, 100_000);
7558         nodes[1].node.process_pending_htlc_forwards();
7559
7560         let events = nodes[1].node.get_and_clear_pending_msg_events();
7561         assert_eq!(events.len(), 1);
7562         let (update_fail_htlc, commitment_signed) = match events[0] {
7563                 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 } } => {
7564                         assert!(update_add_htlcs.is_empty());
7565                         assert!(update_fulfill_htlcs.is_empty());
7566                         assert_eq!(update_fail_htlcs.len(), 1);
7567                         assert!(update_fail_malformed_htlcs.is_empty());
7568                         assert!(update_fee.is_none());
7569                         (update_fail_htlcs[0].clone(), commitment_signed)
7570                 },
7571                 _ => panic!("Unexpected event"),
7572         };
7573         check_added_monitors!(nodes[1], 1);
7574
7575         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7576         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7577
7578         // 10_000 msat as u64, followed by a height of 99 as u32
7579         let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7580         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(99));
7581         expect_payment_failed!(nodes[0], payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7582         nodes[1].node.get_and_clear_pending_events();
7583 }
7584
7585 #[test]
7586 fn test_announce_disable_channels() {
7587         // Create 2 channels between A and B. Disconnect B. Call timer_chan_freshness_every_min and check for generated
7588         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7589
7590         let chanmon_cfgs = create_chanmon_cfgs(2);
7591         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7592         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7593         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7594
7595         let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7596         let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7597         let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7598
7599         // Disconnect peers
7600         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7601         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7602
7603         nodes[0].node.timer_chan_freshness_every_min(); // dirty -> stagged
7604         nodes[0].node.timer_chan_freshness_every_min(); // staged -> fresh
7605         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7606         assert_eq!(msg_events.len(), 3);
7607         for e in msg_events {
7608                 match e {
7609                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7610                                 let short_id = msg.contents.short_channel_id;
7611                                 // Check generated channel_update match list in PendingChannelUpdate
7612                                 if short_id != short_id_1 && short_id != short_id_2 && short_id != short_id_3 {
7613                                         panic!("Generated ChannelUpdate for wrong chan!");
7614                                 }
7615                         },
7616                         _ => panic!("Unexpected event"),
7617                 }
7618         }
7619         // Reconnect peers
7620         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7621         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7622         assert_eq!(reestablish_1.len(), 3);
7623         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7624         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7625         assert_eq!(reestablish_2.len(), 3);
7626
7627         // Reestablish chan_1
7628         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7629         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7630         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7631         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7632         // Reestablish chan_2
7633         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7634         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7635         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7636         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7637         // Reestablish chan_3
7638         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7639         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7640         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7641         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7642
7643         nodes[0].node.timer_chan_freshness_every_min();
7644         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7645 }
7646
7647 #[test]
7648 fn test_bump_penalty_txn_on_revoked_commitment() {
7649         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7650         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7651
7652         let chanmon_cfgs = create_chanmon_cfgs(2);
7653         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7654         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7655         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7656
7657         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7658         let logger = test_utils::TestLogger::new();
7659
7660
7661         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7662         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
7663         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();
7664         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7665
7666         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7667         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7668         assert_eq!(revoked_txn[0].output.len(), 4);
7669         assert_eq!(revoked_txn[0].input.len(), 1);
7670         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7671         let revoked_txid = revoked_txn[0].txid();
7672
7673         let mut penalty_sum = 0;
7674         for outp in revoked_txn[0].output.iter() {
7675                 if outp.script_pubkey.is_v0_p2wsh() {
7676                         penalty_sum += outp.value;
7677                 }
7678         }
7679
7680         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7681         let header_114 = connect_blocks(&nodes[1].block_notifier, 114, 0, false, Default::default());
7682
7683         // Actually revoke tx by claiming a HTLC
7684         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7685         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7686         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_txn[0].clone()] }, 115);
7687         check_added_monitors!(nodes[1], 1);
7688
7689         // One or more justice tx should have been broadcast, check it
7690         let penalty_1;
7691         let feerate_1;
7692         {
7693                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7694                 assert_eq!(node_txn.len(), 3); // justice tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout (broadcasted from ChannelManager)
7695                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7696                 assert_eq!(node_txn[0].output.len(), 1);
7697                 check_spends!(node_txn[0], revoked_txn[0]);
7698                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7699                 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7700                 penalty_1 = node_txn[0].txid();
7701                 node_txn.clear();
7702         };
7703
7704         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7705         let header = connect_blocks(&nodes[1].block_notifier, 3, 115,  true, header.block_hash());
7706         let mut penalty_2 = penalty_1;
7707         let mut feerate_2 = 0;
7708         {
7709                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7710                 assert_eq!(node_txn.len(), 1);
7711                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7712                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7713                         assert_eq!(node_txn[0].output.len(), 1);
7714                         check_spends!(node_txn[0], revoked_txn[0]);
7715                         penalty_2 = node_txn[0].txid();
7716                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7717                         assert_ne!(penalty_2, penalty_1);
7718                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7719                         feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7720                         // Verify 25% bump heuristic
7721                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7722                         node_txn.clear();
7723                 }
7724         }
7725         assert_ne!(feerate_2, 0);
7726
7727         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7728         connect_blocks(&nodes[1].block_notifier, 3, 118, true, header);
7729         let penalty_3;
7730         let mut feerate_3 = 0;
7731         {
7732                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7733                 assert_eq!(node_txn.len(), 1);
7734                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7735                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7736                         assert_eq!(node_txn[0].output.len(), 1);
7737                         check_spends!(node_txn[0], revoked_txn[0]);
7738                         penalty_3 = node_txn[0].txid();
7739                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7740                         assert_ne!(penalty_3, penalty_2);
7741                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7742                         feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7743                         // Verify 25% bump heuristic
7744                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7745                         node_txn.clear();
7746                 }
7747         }
7748         assert_ne!(feerate_3, 0);
7749
7750         nodes[1].node.get_and_clear_pending_events();
7751         nodes[1].node.get_and_clear_pending_msg_events();
7752 }
7753
7754 #[test]
7755 fn test_bump_penalty_txn_on_revoked_htlcs() {
7756         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7757         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7758
7759         let chanmon_cfgs = create_chanmon_cfgs(2);
7760         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7761         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7762         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7763
7764         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7765         // Lock HTLC in both directions
7766         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3_000_000).0;
7767         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7768
7769         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7770         assert_eq!(revoked_local_txn[0].input.len(), 1);
7771         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7772
7773         // Revoke local commitment tx
7774         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7775
7776         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7777         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7778         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
7779         check_closed_broadcast!(nodes[1], false);
7780         check_added_monitors!(nodes[1], 1);
7781
7782         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7783         assert_eq!(revoked_htlc_txn.len(), 4);
7784         if revoked_htlc_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7785                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7786                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7787                 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7788                 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7789                 assert_eq!(revoked_htlc_txn[1].output.len(), 1);
7790                 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7791         } else if revoked_htlc_txn[1].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7792                 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7793                 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7794                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7795                 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7796                 assert_eq!(revoked_htlc_txn[0].output.len(), 1);
7797                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7798         }
7799
7800         // Broadcast set of revoked txn on A
7801         let header_128 = connect_blocks(&nodes[0].block_notifier, 128, 0, true, header.block_hash());
7802         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7803
7804         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7805         nodes[0].block_notifier.block_connected(&Block { header: header_129, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()] }, 129);
7806         let first;
7807         let feerate_1;
7808         let penalty_txn;
7809         {
7810                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7811                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7812                 // Verify claim tx are spending revoked HTLC txn
7813
7814                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7815                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7816                 // which are included in the same block (they are broadcasted because we scan the
7817                 // transactions linearly and generate claims as we go, they likely should be removed in the
7818                 // future).
7819                 assert_eq!(node_txn[0].input.len(), 1);
7820                 check_spends!(node_txn[0], revoked_local_txn[0]);
7821                 assert_eq!(node_txn[1].input.len(), 1);
7822                 check_spends!(node_txn[1], revoked_local_txn[0]);
7823                 assert_eq!(node_txn[2].input.len(), 1);
7824                 check_spends!(node_txn[2], revoked_local_txn[0]);
7825
7826                 // Each of the three justice transactions claim a separate (single) output of the three
7827                 // available, which we check here:
7828                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7829                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7830                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7831
7832                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7833                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7834
7835                 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7836                 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7837                 // a remote commitment tx has already been confirmed).
7838                 check_spends!(node_txn[3], chan.3);
7839
7840                 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7841                 // output, checked above).
7842                 assert_eq!(node_txn[4].input.len(), 2);
7843                 assert_eq!(node_txn[4].output.len(), 1);
7844                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7845                 first = node_txn[4].txid();
7846                 // Store both feerates for later comparison
7847                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[4].output[0].value;
7848                 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7849                 penalty_txn = vec![node_txn[2].clone()];
7850                 node_txn.clear();
7851         }
7852
7853         // Connect one more block to see if bumped penalty are issued for HTLC txn
7854         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7855         nodes[0].block_notifier.block_connected(&Block { header: header_130, txdata: penalty_txn }, 130);
7856         {
7857                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7858                 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7859
7860                 check_spends!(node_txn[0], revoked_local_txn[0]);
7861                 check_spends!(node_txn[1], revoked_local_txn[0]);
7862                 // Note that these are both bogus - they spend outputs already claimed in block 129:
7863                 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output  {
7864                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7865                 } else {
7866                         assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7867                         assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7868                 }
7869
7870                 node_txn.clear();
7871         };
7872
7873         // Few more blocks to confirm penalty txn
7874         let header_135 = connect_blocks(&nodes[0].block_notifier, 5, 130, true, header_130.block_hash());
7875         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7876         let header_144 = connect_blocks(&nodes[0].block_notifier, 9, 135, true, header_135);
7877         let node_txn = {
7878                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7879                 assert_eq!(node_txn.len(), 1);
7880
7881                 assert_eq!(node_txn[0].input.len(), 2);
7882                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7883                 // Verify bumped tx is different and 25% bump heuristic
7884                 assert_ne!(first, node_txn[0].txid());
7885                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7886                 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7887                 assert!(feerate_2 * 100 > feerate_1 * 125);
7888                 let txn = vec![node_txn[0].clone()];
7889                 node_txn.clear();
7890                 txn
7891         };
7892         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7893         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7894         nodes[0].block_notifier.block_connected(&Block { header: header_145, txdata: node_txn }, 145);
7895         connect_blocks(&nodes[0].block_notifier, 20, 145, true, header_145.block_hash());
7896         {
7897                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7898                 // We verify than no new transaction has been broadcast because previously
7899                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7900                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7901                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7902                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7903                 // up bumped justice generation.
7904                 assert_eq!(node_txn.len(), 0);
7905                 node_txn.clear();
7906         }
7907         check_closed_broadcast!(nodes[0], false);
7908         check_added_monitors!(nodes[0], 1);
7909 }
7910
7911 #[test]
7912 fn test_bump_penalty_txn_on_remote_commitment() {
7913         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7914         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7915
7916         // Create 2 HTLCs
7917         // Provide preimage for one
7918         // Check aggregation
7919
7920         let chanmon_cfgs = create_chanmon_cfgs(2);
7921         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7922         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7923         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7924
7925         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7926         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7927         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7928
7929         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7930         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7931         assert_eq!(remote_txn[0].output.len(), 4);
7932         assert_eq!(remote_txn[0].input.len(), 1);
7933         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7934
7935         // Claim a HTLC without revocation (provide B monitor with preimage)
7936         nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000);
7937         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7938         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
7939         check_added_monitors!(nodes[1], 2);
7940
7941         // One or more claim tx should have been broadcast, check it
7942         let timeout;
7943         let preimage;
7944         let feerate_timeout;
7945         let feerate_preimage;
7946         {
7947                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7948                 assert_eq!(node_txn.len(), 5); // 2 * claim tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout + local HTLC-success (broadcasted from ChannelManager)
7949                 assert_eq!(node_txn[0].input.len(), 1);
7950                 assert_eq!(node_txn[1].input.len(), 1);
7951                 check_spends!(node_txn[0], remote_txn[0]);
7952                 check_spends!(node_txn[1], remote_txn[0]);
7953                 check_spends!(node_txn[2], chan.3);
7954                 check_spends!(node_txn[3], node_txn[2]);
7955                 check_spends!(node_txn[4], node_txn[2]);
7956                 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7957                         timeout = node_txn[0].txid();
7958                         let index = node_txn[0].input[0].previous_output.vout;
7959                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7960                         feerate_timeout = fee * 1000 / node_txn[0].get_weight() as u64;
7961
7962                         preimage = node_txn[1].txid();
7963                         let index = node_txn[1].input[0].previous_output.vout;
7964                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7965                         feerate_preimage = fee * 1000 / node_txn[1].get_weight() as u64;
7966                 } else {
7967                         timeout = node_txn[1].txid();
7968                         let index = node_txn[1].input[0].previous_output.vout;
7969                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7970                         feerate_timeout = fee * 1000 / node_txn[1].get_weight() as u64;
7971
7972                         preimage = node_txn[0].txid();
7973                         let index = node_txn[0].input[0].previous_output.vout;
7974                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7975                         feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7976                 }
7977                 node_txn.clear();
7978         };
7979         assert_ne!(feerate_timeout, 0);
7980         assert_ne!(feerate_preimage, 0);
7981
7982         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7983         connect_blocks(&nodes[1].block_notifier, 15, 1,  true, header.block_hash());
7984         {
7985                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7986                 assert_eq!(node_txn.len(), 2);
7987                 assert_eq!(node_txn[0].input.len(), 1);
7988                 assert_eq!(node_txn[1].input.len(), 1);
7989                 check_spends!(node_txn[0], remote_txn[0]);
7990                 check_spends!(node_txn[1], remote_txn[0]);
7991                 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7992                         let index = node_txn[0].input[0].previous_output.vout;
7993                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7994                         let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7995                         assert!(new_feerate * 100 > feerate_timeout * 125);
7996                         assert_ne!(timeout, node_txn[0].txid());
7997
7998                         let index = node_txn[1].input[0].previous_output.vout;
7999                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
8000                         let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
8001                         assert!(new_feerate * 100 > feerate_preimage * 125);
8002                         assert_ne!(preimage, node_txn[1].txid());
8003                 } else {
8004                         let index = node_txn[1].input[0].previous_output.vout;
8005                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
8006                         let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
8007                         assert!(new_feerate * 100 > feerate_timeout * 125);
8008                         assert_ne!(timeout, node_txn[1].txid());
8009
8010                         let index = node_txn[0].input[0].previous_output.vout;
8011                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8012                         let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
8013                         assert!(new_feerate * 100 > feerate_preimage * 125);
8014                         assert_ne!(preimage, node_txn[0].txid());
8015                 }
8016                 node_txn.clear();
8017         }
8018
8019         nodes[1].node.get_and_clear_pending_events();
8020         nodes[1].node.get_and_clear_pending_msg_events();
8021 }
8022
8023 #[test]
8024 fn test_set_outpoints_partial_claiming() {
8025         // - remote party claim tx, new bump tx
8026         // - disconnect remote claiming tx, new bump
8027         // - disconnect tx, see no tx anymore
8028         let chanmon_cfgs = create_chanmon_cfgs(2);
8029         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8030         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8031         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8032
8033         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8034         let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
8035         let payment_preimage_2 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
8036
8037         // Remote commitment txn with 4 outputs: to_local, to_remote, 2 outgoing HTLC
8038         let remote_txn = get_local_commitment_txn!(nodes[1], chan.2);
8039         assert_eq!(remote_txn.len(), 3);
8040         assert_eq!(remote_txn[0].output.len(), 4);
8041         assert_eq!(remote_txn[0].input.len(), 1);
8042         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
8043         check_spends!(remote_txn[1], remote_txn[0]);
8044         check_spends!(remote_txn[2], remote_txn[0]);
8045
8046         // Connect blocks on node A to advance height towards TEST_FINAL_CLTV
8047         let prev_header_100 = connect_blocks(&nodes[1].block_notifier, 100, 0, false, Default::default());
8048         // Provide node A with both preimage
8049         nodes[0].node.claim_funds(payment_preimage_1, &None, 3_000_000);
8050         nodes[0].node.claim_funds(payment_preimage_2, &None, 3_000_000);
8051         check_added_monitors!(nodes[0], 2);
8052         nodes[0].node.get_and_clear_pending_events();
8053         nodes[0].node.get_and_clear_pending_msg_events();
8054
8055         // Connect blocks on node A commitment transaction
8056         let header = BlockHeader { version: 0x20000000, prev_blockhash: prev_header_100, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8057         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 101);
8058         check_closed_broadcast!(nodes[0], false);
8059         check_added_monitors!(nodes[0], 1);
8060         // Verify node A broadcast tx claiming both HTLCs
8061         {
8062                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8063                 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-Success*2
8064                 assert_eq!(node_txn.len(), 4);
8065                 check_spends!(node_txn[0], remote_txn[0]);
8066                 check_spends!(node_txn[1], chan.3);
8067                 check_spends!(node_txn[2], node_txn[1]);
8068                 check_spends!(node_txn[3], node_txn[1]);
8069                 assert_eq!(node_txn[0].input.len(), 2);
8070                 node_txn.clear();
8071         }
8072
8073         // Connect blocks on node B
8074         connect_blocks(&nodes[1].block_notifier, 135, 0, false, Default::default());
8075         check_closed_broadcast!(nodes[1], false);
8076         check_added_monitors!(nodes[1], 1);
8077         // Verify node B broadcast 2 HTLC-timeout txn
8078         let partial_claim_tx = {
8079                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8080                 assert_eq!(node_txn.len(), 3);
8081                 check_spends!(node_txn[1], node_txn[0]);
8082                 check_spends!(node_txn[2], node_txn[0]);
8083                 assert_eq!(node_txn[1].input.len(), 1);
8084                 assert_eq!(node_txn[2].input.len(), 1);
8085                 node_txn[1].clone()
8086         };
8087
8088         // Broadcast partial claim on node A, should regenerate a claiming tx with HTLC dropped
8089         let header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8090         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![partial_claim_tx.clone()] }, 102);
8091         {
8092                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8093                 assert_eq!(node_txn.len(), 1);
8094                 check_spends!(node_txn[0], remote_txn[0]);
8095                 assert_eq!(node_txn[0].input.len(), 1); //dropped HTLC
8096                 node_txn.clear();
8097         }
8098         nodes[0].node.get_and_clear_pending_msg_events();
8099
8100         // Disconnect last block on node A, should regenerate a claiming tx with HTLC dropped
8101         nodes[0].block_notifier.block_disconnected(&header, 102);
8102         {
8103                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8104                 assert_eq!(node_txn.len(), 1);
8105                 check_spends!(node_txn[0], remote_txn[0]);
8106                 assert_eq!(node_txn[0].input.len(), 2); //resurrected HTLC
8107                 node_txn.clear();
8108         }
8109
8110         //// Disconnect one more block and then reconnect multiple no transaction should be generated
8111         nodes[0].block_notifier.block_disconnected(&header, 101);
8112         connect_blocks(&nodes[1].block_notifier, 15, 101, false, prev_header_100);
8113         {
8114                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8115                 assert_eq!(node_txn.len(), 0);
8116                 node_txn.clear();
8117         }
8118 }
8119
8120 #[test]
8121 fn test_counterparty_raa_skip_no_crash() {
8122         // Previously, if our counterparty sent two RAAs in a row without us having provided a
8123         // commitment transaction, we would have happily carried on and provided them the next
8124         // commitment transaction based on one RAA forward. This would probably eventually have led to
8125         // channel closure, but it would not have resulted in funds loss. Still, our
8126         // EnforcingChannelKeys would have paniced as it doesn't like jumps into the future. Here, we
8127         // check simply that the channel is closed in response to such an RAA, but don't check whether
8128         // we decide to punish our counterparty for revoking their funds (as we don't currently
8129         // implement that).
8130         let chanmon_cfgs = create_chanmon_cfgs(2);
8131         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8132         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8133         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8134         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8135
8136         let mut guard = nodes[0].node.channel_state.lock().unwrap();
8137         let keys = &guard.by_id.get_mut(&channel_id).unwrap().holder_keys;
8138         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8139         let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8140                 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8141         let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8142
8143         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8144                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8145         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8146         check_added_monitors!(nodes[1], 1);
8147 }
8148
8149 #[test]
8150 fn test_bump_txn_sanitize_tracking_maps() {
8151         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8152         // verify we clean then right after expiration of ANTI_REORG_DELAY.
8153
8154         let chanmon_cfgs = create_chanmon_cfgs(2);
8155         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8156         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8157         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8158
8159         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8160         // Lock HTLC in both directions
8161         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8162         route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8163
8164         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8165         assert_eq!(revoked_local_txn[0].input.len(), 1);
8166         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8167
8168         // Revoke local commitment tx
8169         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 9_000_000);
8170
8171         // Broadcast set of revoked txn on A
8172         let header_128 = connect_blocks(&nodes[0].block_notifier, 128, 0,  false, Default::default());
8173         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8174
8175         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8176         nodes[0].block_notifier.block_connected(&Block { header: header_129, txdata: vec![revoked_local_txn[0].clone()] }, 129);
8177         check_closed_broadcast!(nodes[0], false);
8178         check_added_monitors!(nodes[0], 1);
8179         let penalty_txn = {
8180                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8181                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8182                 check_spends!(node_txn[0], revoked_local_txn[0]);
8183                 check_spends!(node_txn[1], revoked_local_txn[0]);
8184                 check_spends!(node_txn[2], revoked_local_txn[0]);
8185                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8186                 node_txn.clear();
8187                 penalty_txn
8188         };
8189         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8190         nodes[0].block_notifier.block_connected(&Block { header: header_130, txdata: penalty_txn }, 130);
8191         connect_blocks(&nodes[0].block_notifier, 5, 130,  false, header_130.block_hash());
8192         {
8193                 let monitors = nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap();
8194                 if let Some(monitor) = monitors.get(&OutPoint { txid: chan.3.txid(), index: 0 }) {
8195                         assert!(monitor.onchain_tx_handler.pending_claim_requests.is_empty());
8196                         assert!(monitor.onchain_tx_handler.claimable_outpoints.is_empty());
8197                 }
8198         }
8199 }
8200
8201 #[test]
8202 fn test_override_channel_config() {
8203         let chanmon_cfgs = create_chanmon_cfgs(2);
8204         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8205         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8206         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8207
8208         // Node0 initiates a channel to node1 using the override config.
8209         let mut override_config = UserConfig::default();
8210         override_config.own_channel_config.our_to_self_delay = 200;
8211
8212         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8213
8214         // Assert the channel created by node0 is using the override config.
8215         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8216         assert_eq!(res.channel_flags, 0);
8217         assert_eq!(res.to_self_delay, 200);
8218 }
8219
8220 #[test]
8221 fn test_override_0msat_htlc_minimum() {
8222         let mut zero_config = UserConfig::default();
8223         zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8224         let chanmon_cfgs = create_chanmon_cfgs(2);
8225         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8226         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8227         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8228
8229         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8230         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8231         assert_eq!(res.htlc_minimum_msat, 1);
8232
8233         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8234         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8235         assert_eq!(res.htlc_minimum_msat, 1);
8236 }
8237
8238 #[test]
8239 fn test_simple_payment_secret() {
8240         // Simple test of sending a payment with a payment_secret present. This does not use any AMP
8241         // features, however.
8242         let chanmon_cfgs = create_chanmon_cfgs(3);
8243         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8244         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8245         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8246
8247         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8248         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
8249         let logger = test_utils::TestLogger::new();
8250
8251         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8252         let payment_secret = PaymentSecret([0xdb; 32]);
8253         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8254         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();
8255         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2]]], 100000, payment_hash, Some(payment_secret.clone()));
8256         // Claiming with all the correct values but the wrong secret should result in nothing...
8257         assert_eq!(nodes[2].node.claim_funds(payment_preimage, &None, 100_000), false);
8258         assert_eq!(nodes[2].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 100_000), false);
8259         // ...but with the right secret we should be able to claim all the way back
8260         claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage, Some(payment_secret.clone()), 100_000);
8261 }
8262
8263 #[test]
8264 fn test_simple_mpp() {
8265         // Simple test of sending a multi-path payment.
8266         let chanmon_cfgs = create_chanmon_cfgs(4);
8267         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8268         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8269         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8270
8271         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8272         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8273         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8274         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8275         let logger = test_utils::TestLogger::new();
8276
8277         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8278         let payment_secret = PaymentSecret([0xdb; 32]);
8279         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8280         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();
8281         let path = route.paths[0].clone();
8282         route.paths.push(path);
8283         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8284         route.paths[0][0].short_channel_id = chan_1_id;
8285         route.paths[0][1].short_channel_id = chan_3_id;
8286         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8287         route.paths[1][0].short_channel_id = chan_2_id;
8288         route.paths[1][1].short_channel_id = chan_4_id;
8289         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, Some(payment_secret.clone()));
8290         // Claiming with all the correct values but the wrong secret should result in nothing...
8291         assert_eq!(nodes[3].node.claim_funds(payment_preimage, &None, 200_000), false);
8292         assert_eq!(nodes[3].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 200_000), false);
8293         // ...but with the right secret we should be able to claim all the way back
8294         claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage, Some(payment_secret), 200_000);
8295 }
8296
8297 #[test]
8298 fn test_update_err_monitor_lockdown() {
8299         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8300         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8301         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8302         //
8303         // This scenario may happen in a watchtower setup, where watchtower process a block height
8304         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8305         // commitment at same time.
8306
8307         let chanmon_cfgs = create_chanmon_cfgs(2);
8308         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8309         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8310         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8311
8312         // Create some initial channel
8313         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8314         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8315
8316         // Rebalance the network to generate htlc in the two directions
8317         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8318
8319         // Route a HTLC from node 0 to node 1 (but don't settle)
8320         let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8321
8322         // Copy SimpleManyChannelMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8323         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8324         let chain_monitor = chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet);
8325         let watchtower = {
8326                 let monitors = nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap();
8327                 let monitor = monitors.get(&outpoint).unwrap();
8328                 let mut w = test_utils::TestVecWriter(Vec::new());
8329                 monitor.write_for_disk(&mut w).unwrap();
8330                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
8331                                 &mut ::std::io::Cursor::new(&w.0)).unwrap().1;
8332                 assert!(new_monitor == *monitor);
8333                 let watchtower = test_utils::TestChannelMonitor::new(&chain_monitor, &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator);
8334                 assert!(watchtower.add_monitor(outpoint, new_monitor).is_ok());
8335                 watchtower
8336         };
8337         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8338         watchtower.simple_monitor.block_connected(&header, 200, &vec![], &vec![]);
8339
8340         // Try to update ChannelMonitor
8341         assert!(nodes[1].node.claim_funds(preimage, &None, 9_000_000));
8342         check_added_monitors!(nodes[1], 1);
8343         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8344         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8345         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8346         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8347                 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8348                         if let Err(_) =  watchtower.simple_monitor.update_monitor(outpoint, update.clone()) {} else { assert!(false); }
8349                         if let Ok(_) = nodes[0].chan_monitor.update_monitor(outpoint, update) {} else { assert!(false); }
8350                 } else { assert!(false); }
8351         } else { assert!(false); };
8352         // Our local monitor is in-sync and hasn't processed yet timeout
8353         check_added_monitors!(nodes[0], 1);
8354         let events = nodes[0].node.get_and_clear_pending_events();
8355         assert_eq!(events.len(), 1);
8356 }
8357
8358 #[test]
8359 fn test_concurrent_monitor_claim() {
8360         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8361         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8362         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8363         // state N+1 confirms. Alice claims output from state N+1.
8364
8365         let chanmon_cfgs = create_chanmon_cfgs(2);
8366         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8367         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8368         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8369
8370         // Create some initial channel
8371         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8372         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8373
8374         // Rebalance the network to generate htlc in the two directions
8375         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8376
8377         // Route a HTLC from node 0 to node 1 (but don't settle)
8378         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8379
8380         // Copy SimpleManyChannelMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8381         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8382         let chain_monitor = chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet);
8383         let watchtower_alice = {
8384                 let monitors = nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap();
8385                 let monitor = monitors.get(&outpoint).unwrap();
8386                 let mut w = test_utils::TestVecWriter(Vec::new());
8387                 monitor.write_for_disk(&mut w).unwrap();
8388                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
8389                                 &mut ::std::io::Cursor::new(&w.0)).unwrap().1;
8390                 assert!(new_monitor == *monitor);
8391                 let watchtower = test_utils::TestChannelMonitor::new(&chain_monitor, &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator);
8392                 assert!(watchtower.add_monitor(outpoint, new_monitor).is_ok());
8393                 watchtower
8394         };
8395         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8396         watchtower_alice.simple_monitor.block_connected(&header, 135, &vec![], &vec![]);
8397
8398         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8399         {
8400                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8401                 assert_eq!(txn.len(), 2);
8402                 txn.clear();
8403         }
8404
8405         // Copy SimpleManyChannelMonitor to simulate watchtower Bob and make it receive a commitment update first.
8406         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8407         let chain_monitor = chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet);
8408         let watchtower_bob = {
8409                 let monitors = nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap();
8410                 let monitor = monitors.get(&outpoint).unwrap();
8411                 let mut w = test_utils::TestVecWriter(Vec::new());
8412                 monitor.write_for_disk(&mut w).unwrap();
8413                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
8414                                 &mut ::std::io::Cursor::new(&w.0)).unwrap().1;
8415                 assert!(new_monitor == *monitor);
8416                 let watchtower = test_utils::TestChannelMonitor::new(&chain_monitor, &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator);
8417                 assert!(watchtower.add_monitor(outpoint, new_monitor).is_ok());
8418                 watchtower
8419         };
8420         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8421         watchtower_bob.simple_monitor.block_connected(&header, 134, &vec![], &vec![]);
8422
8423         // Route another payment to generate another update with still previous HTLC pending
8424         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
8425         {
8426                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
8427                 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();
8428                 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
8429         }
8430         check_added_monitors!(nodes[1], 1);
8431
8432         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8433         assert_eq!(updates.update_add_htlcs.len(), 1);
8434         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8435         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8436                 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8437                         // Watchtower Alice should already have seen the block and reject the update
8438                         if let Err(_) =  watchtower_alice.simple_monitor.update_monitor(outpoint, update.clone()) {} else { assert!(false); }
8439                         if let Ok(_) = watchtower_bob.simple_monitor.update_monitor(outpoint, update.clone()) {} else { assert!(false); }
8440                         if let Ok(_) = nodes[0].chan_monitor.update_monitor(outpoint, update) {} else { assert!(false); }
8441                 } else { assert!(false); }
8442         } else { assert!(false); };
8443         // Our local monitor is in-sync and hasn't processed yet timeout
8444         check_added_monitors!(nodes[0], 1);
8445
8446         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8447         watchtower_bob.simple_monitor.block_connected(&header, 135, &vec![], &vec![]);
8448
8449         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8450         let bob_state_y;
8451         {
8452                 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8453                 assert_eq!(txn.len(), 2);
8454                 bob_state_y = txn[0].clone();
8455                 txn.clear();
8456         };
8457
8458         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8459         watchtower_alice.simple_monitor.block_connected(&header, 136, &vec![&bob_state_y][..], &vec![]);
8460         {
8461                 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8462                 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8463                 // the onchain detection of the HTLC output
8464                 assert_eq!(htlc_txn.len(), 2);
8465                 check_spends!(htlc_txn[0], bob_state_y);
8466                 check_spends!(htlc_txn[1], bob_state_y);
8467         }
8468 }