d106f0c7ddb4723aa802082fc0b5c1e24abef224
[rust-lightning] / lightning / src / ln / functional_tests.rs
1 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
2 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
3 //! claim outputs on-chain.
4
5 use chain::Watch;
6 use chain::transaction::OutPoint;
7 use chain::keysinterface::{ChannelKeys, KeysInterface, SpendableOutputDescriptor};
8 use chain::chaininterface::ChainListener;
9 use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
10 use ln::channelmanager::{ChannelManager,ChannelManagerReadArgs,HTLCForwardInfo,RAACommitmentOrder, PaymentPreimage, PaymentHash, PaymentSecret, PaymentSendFailure, BREAKDOWN_TIMEOUT};
11 use ln::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
12 use ln::channelmonitor;
13 use ln::channel::{Channel, ChannelError};
14 use ln::{chan_utils, onion_utils};
15 use routing::router::{Route, RouteHop, get_route};
16 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
17 use ln::msgs;
18 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler,HTLCFailChannelUpdate, ErrorAction, OptionalField};
19 use util::enforcing_trait_impls::EnforcingChannelKeys;
20 use util::{byte_utils, test_utils};
21 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
22 use util::errors::APIError;
23 use util::ser::{Writeable, Writer, ReadableArgs, Readable};
24 use util::config::UserConfig;
25
26 use bitcoin::util::hash::BitcoinHash;
27 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
28 use bitcoin::hashes::HashEngine;
29 use bitcoin::hash_types::{Txid, BlockHash, WPubkeyHash};
30 use bitcoin::util::bip143;
31 use bitcoin::util::address::Address;
32 use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
33 use bitcoin::blockdata::block::{Block, BlockHeader};
34 use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType, OutPoint as BitcoinOutPoint};
35 use bitcoin::blockdata::script::{Builder, Script};
36 use bitcoin::blockdata::opcodes;
37 use bitcoin::blockdata::constants::genesis_block;
38 use bitcoin::network::constants::Network;
39
40 use bitcoin::hashes::sha256::Hash as Sha256;
41 use bitcoin::hashes::Hash;
42
43 use bitcoin::secp256k1::{Secp256k1, Message};
44 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
45
46 use regex;
47
48 use std::collections::{BTreeSet, HashMap, HashSet};
49 use std::default::Default;
50 use std::sync::{Arc, Mutex};
51 use std::sync::atomic::Ordering;
52 use std::{mem, io};
53
54 use ln::functional_test_utils::*;
55
56 #[test]
57 fn test_insane_channel_opens() {
58         // Stand up a network of 2 nodes
59         let chanmon_cfgs = create_chanmon_cfgs(2);
60         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
61         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
62         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
63
64         // Instantiate channel parameters where we push the maximum msats given our
65         // funding satoshis
66         let channel_value_sat = 31337; // same as funding satoshis
67         let channel_reserve_satoshis = Channel::<EnforcingChannelKeys>::get_remote_channel_reserve_satoshis(channel_value_sat);
68         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
69
70         // Have node0 initiate a channel to node1 with aforementioned parameters
71         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
72
73         // Extract the channel open message from node0 to node1
74         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
75
76         // Test helper that asserts we get the correct error string given a mutator
77         // that supposedly makes the channel open message insane
78         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
79                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
80                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
81                 assert_eq!(msg_events.len(), 1);
82                 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
83                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
84                         match action {
85                                 &ErrorAction::SendErrorMessage { .. } => {
86                                         nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
87                                 },
88                                 _ => panic!("unexpected event!"),
89                         }
90                 } else { assert!(false); }
91         };
92
93         use ln::channel::MAX_FUNDING_SATOSHIS;
94         use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
95
96         // Test all mutations that would make the channel open message insane
97         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 });
98
99         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
100
101         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 });
102
103         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
104
105         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 });
106
107         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 });
108
109         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 });
110
111         insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
112
113         insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
114 }
115
116 #[test]
117 fn test_async_inbound_update_fee() {
118         let chanmon_cfgs = create_chanmon_cfgs(2);
119         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
120         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
121         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
122         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
123         let logger = test_utils::TestLogger::new();
124         let channel_id = chan.2;
125
126         // balancing
127         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
128
129         // A                                        B
130         // update_fee                            ->
131         // send (1) commitment_signed            -.
132         //                                       <- update_add_htlc/commitment_signed
133         // send (2) RAA (awaiting remote revoke) -.
134         // (1) commitment_signed is delivered    ->
135         //                                       .- send (3) RAA (awaiting remote revoke)
136         // (2) RAA is delivered                  ->
137         //                                       .- send (4) commitment_signed
138         //                                       <- (3) RAA is delivered
139         // send (5) commitment_signed            -.
140         //                                       <- (4) commitment_signed is delivered
141         // send (6) RAA                          -.
142         // (5) commitment_signed is delivered    ->
143         //                                       <- RAA
144         // (6) RAA is delivered                  ->
145
146         // First nodes[0] generates an update_fee
147         nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
148         check_added_monitors!(nodes[0], 1);
149
150         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
151         assert_eq!(events_0.len(), 1);
152         let (update_msg, commitment_signed) = match events_0[0] { // (1)
153                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
154                         (update_fee.as_ref(), commitment_signed)
155                 },
156                 _ => panic!("Unexpected event"),
157         };
158
159         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
160
161         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
162         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
163         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
164         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();
165         check_added_monitors!(nodes[1], 1);
166
167         let payment_event = {
168                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
169                 assert_eq!(events_1.len(), 1);
170                 SendEvent::from_event(events_1.remove(0))
171         };
172         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
173         assert_eq!(payment_event.msgs.len(), 1);
174
175         // ...now when the messages get delivered everyone should be happy
176         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
177         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
178         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
179         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
180         check_added_monitors!(nodes[0], 1);
181
182         // deliver(1), generate (3):
183         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
184         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
185         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
186         check_added_monitors!(nodes[1], 1);
187
188         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
189         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
190         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
191         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
192         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
193         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
194         assert!(bs_update.update_fee.is_none()); // (4)
195         check_added_monitors!(nodes[1], 1);
196
197         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
198         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
199         assert!(as_update.update_add_htlcs.is_empty()); // (5)
200         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
201         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
202         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
203         assert!(as_update.update_fee.is_none()); // (5)
204         check_added_monitors!(nodes[0], 1);
205
206         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
207         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
208         // only (6) so get_event_msg's assert(len == 1) passes
209         check_added_monitors!(nodes[0], 1);
210
211         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
212         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
213         check_added_monitors!(nodes[1], 1);
214
215         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
216         check_added_monitors!(nodes[0], 1);
217
218         let events_2 = nodes[0].node.get_and_clear_pending_events();
219         assert_eq!(events_2.len(), 1);
220         match events_2[0] {
221                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
222                 _ => panic!("Unexpected event"),
223         }
224
225         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
226         check_added_monitors!(nodes[1], 1);
227 }
228
229 #[test]
230 fn test_update_fee_unordered_raa() {
231         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
232         // crash in an earlier version of the update_fee patch)
233         let chanmon_cfgs = create_chanmon_cfgs(2);
234         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
235         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
236         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
237         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
238         let channel_id = chan.2;
239         let logger = test_utils::TestLogger::new();
240
241         // balancing
242         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
243
244         // First nodes[0] generates an update_fee
245         nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
246         check_added_monitors!(nodes[0], 1);
247
248         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
249         assert_eq!(events_0.len(), 1);
250         let update_msg = match events_0[0] { // (1)
251                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
252                         update_fee.as_ref()
253                 },
254                 _ => panic!("Unexpected event"),
255         };
256
257         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
258
259         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
260         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
261         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
262         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();
263         check_added_monitors!(nodes[1], 1);
264
265         let payment_event = {
266                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
267                 assert_eq!(events_1.len(), 1);
268                 SendEvent::from_event(events_1.remove(0))
269         };
270         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
271         assert_eq!(payment_event.msgs.len(), 1);
272
273         // ...now when the messages get delivered everyone should be happy
274         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
275         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
276         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
277         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
278         check_added_monitors!(nodes[0], 1);
279
280         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
281         check_added_monitors!(nodes[1], 1);
282
283         // We can't continue, sadly, because our (1) now has a bogus signature
284 }
285
286 #[test]
287 fn test_multi_flight_update_fee() {
288         let chanmon_cfgs = create_chanmon_cfgs(2);
289         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
290         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
291         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
292         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
293         let channel_id = chan.2;
294
295         // A                                        B
296         // update_fee/commitment_signed          ->
297         //                                       .- send (1) RAA and (2) commitment_signed
298         // update_fee (never committed)          ->
299         // (3) update_fee                        ->
300         // We have to manually generate the above update_fee, it is allowed by the protocol but we
301         // don't track which updates correspond to which revoke_and_ack responses so we're in
302         // AwaitingRAA mode and will not generate the update_fee yet.
303         //                                       <- (1) RAA delivered
304         // (3) is generated and send (4) CS      -.
305         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
306         // know the per_commitment_point to use for it.
307         //                                       <- (2) commitment_signed delivered
308         // revoke_and_ack                        ->
309         //                                          B should send no response here
310         // (4) commitment_signed delivered       ->
311         //                                       <- RAA/commitment_signed delivered
312         // revoke_and_ack                        ->
313
314         // First nodes[0] generates an update_fee
315         let initial_feerate = get_feerate!(nodes[0], channel_id);
316         nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
317         check_added_monitors!(nodes[0], 1);
318
319         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
320         assert_eq!(events_0.len(), 1);
321         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
322                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
323                         (update_fee.as_ref().unwrap(), commitment_signed)
324                 },
325                 _ => panic!("Unexpected event"),
326         };
327
328         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
329         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
330         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
331         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
332         check_added_monitors!(nodes[1], 1);
333
334         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
335         // transaction:
336         nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
337         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
338         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
339
340         // Create the (3) update_fee message that nodes[0] will generate before it does...
341         let mut update_msg_2 = msgs::UpdateFee {
342                 channel_id: update_msg_1.channel_id.clone(),
343                 feerate_per_kw: (initial_feerate + 30) as u32,
344         };
345
346         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
347
348         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
349         // Deliver (3)
350         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
351
352         // Deliver (1), generating (3) and (4)
353         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
354         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
355         check_added_monitors!(nodes[0], 1);
356         assert!(as_second_update.update_add_htlcs.is_empty());
357         assert!(as_second_update.update_fulfill_htlcs.is_empty());
358         assert!(as_second_update.update_fail_htlcs.is_empty());
359         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
360         // Check that the update_fee newly generated matches what we delivered:
361         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
362         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
363
364         // Deliver (2) commitment_signed
365         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
366         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
367         check_added_monitors!(nodes[0], 1);
368         // No commitment_signed so get_event_msg's assert(len == 1) passes
369
370         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
371         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
372         check_added_monitors!(nodes[1], 1);
373
374         // Delever (4)
375         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
376         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
377         check_added_monitors!(nodes[1], 1);
378
379         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
380         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
381         check_added_monitors!(nodes[0], 1);
382
383         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
384         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
385         // No commitment_signed so get_event_msg's assert(len == 1) passes
386         check_added_monitors!(nodes[0], 1);
387
388         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
389         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
390         check_added_monitors!(nodes[1], 1);
391 }
392
393 #[test]
394 fn test_1_conf_open() {
395         // Previously, if the minium_depth config was set to 1, we'd never send a funding_locked. This
396         // tests that we properly send one in that case.
397         let mut alice_config = UserConfig::default();
398         alice_config.own_channel_config.minimum_depth = 1;
399         alice_config.channel_options.announced_channel = true;
400         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
401         let mut bob_config = UserConfig::default();
402         bob_config.own_channel_config.minimum_depth = 1;
403         bob_config.channel_options.announced_channel = true;
404         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
405         let chanmon_cfgs = create_chanmon_cfgs(2);
406         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
407         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(alice_config), Some(bob_config)]);
408         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
409
410         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
411         let block = Block {
412                 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
413                 txdata: vec![tx],
414         };
415         connect_block(&nodes[1], &block, 1);
416         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()));
417
418         connect_block(&nodes[0], &block, 1);
419         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
420         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
421
422         for node in nodes {
423                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
424                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
425                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
426         }
427 }
428
429 fn do_test_sanity_on_in_flight_opens(steps: u8) {
430         // Previously, we had issues deserializing channels when we hadn't connected the first block
431         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
432         // serialization round-trips and simply do steps towards opening a channel and then drop the
433         // Node objects.
434
435         let chanmon_cfgs = create_chanmon_cfgs(2);
436         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
437         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
438         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
439
440         if steps & 0b1000_0000 != 0{
441                 let block = Block {
442                         header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
443                         txdata: vec![],
444                 };
445                 connect_block(&nodes[0], &block, 1);
446                 connect_block(&nodes[1], &block, 1);
447         }
448
449         if steps & 0x0f == 0 { return; }
450         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
451         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
452
453         if steps & 0x0f == 1 { return; }
454         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
455         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
456
457         if steps & 0x0f == 2 { return; }
458         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
459
460         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
461
462         if steps & 0x0f == 3 { return; }
463         nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
464         check_added_monitors!(nodes[0], 0);
465         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
466
467         if steps & 0x0f == 4 { return; }
468         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
469         {
470                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
471                 assert_eq!(added_monitors.len(), 1);
472                 assert_eq!(added_monitors[0].0, funding_output);
473                 added_monitors.clear();
474         }
475         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
476
477         if steps & 0x0f == 5 { return; }
478         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
479         {
480                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
481                 assert_eq!(added_monitors.len(), 1);
482                 assert_eq!(added_monitors[0].0, funding_output);
483                 added_monitors.clear();
484         }
485
486         let events_4 = nodes[0].node.get_and_clear_pending_events();
487         assert_eq!(events_4.len(), 1);
488         match events_4[0] {
489                 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
490                         assert_eq!(user_channel_id, 42);
491                         assert_eq!(*funding_txo, funding_output);
492                 },
493                 _ => panic!("Unexpected event"),
494         };
495
496         if steps & 0x0f == 6 { return; }
497         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx);
498
499         if steps & 0x0f == 7 { return; }
500         confirm_transaction(&nodes[0], &tx);
501         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
502 }
503
504 #[test]
505 fn test_sanity_on_in_flight_opens() {
506         do_test_sanity_on_in_flight_opens(0);
507         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
508         do_test_sanity_on_in_flight_opens(1);
509         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
510         do_test_sanity_on_in_flight_opens(2);
511         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
512         do_test_sanity_on_in_flight_opens(3);
513         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
514         do_test_sanity_on_in_flight_opens(4);
515         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
516         do_test_sanity_on_in_flight_opens(5);
517         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
518         do_test_sanity_on_in_flight_opens(6);
519         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
520         do_test_sanity_on_in_flight_opens(7);
521         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
522         do_test_sanity_on_in_flight_opens(8);
523         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
524 }
525
526 #[test]
527 fn test_update_fee_vanilla() {
528         let chanmon_cfgs = create_chanmon_cfgs(2);
529         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
530         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
531         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
532         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
533         let channel_id = chan.2;
534
535         let feerate = get_feerate!(nodes[0], channel_id);
536         nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
537         check_added_monitors!(nodes[0], 1);
538
539         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
540         assert_eq!(events_0.len(), 1);
541         let (update_msg, commitment_signed) = match events_0[0] {
542                         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 } } => {
543                         (update_fee.as_ref(), commitment_signed)
544                 },
545                 _ => panic!("Unexpected event"),
546         };
547         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
548
549         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
550         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
551         check_added_monitors!(nodes[1], 1);
552
553         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
554         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
555         check_added_monitors!(nodes[0], 1);
556
557         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
558         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
559         // No commitment_signed so get_event_msg's assert(len == 1) passes
560         check_added_monitors!(nodes[0], 1);
561
562         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
563         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
564         check_added_monitors!(nodes[1], 1);
565 }
566
567 #[test]
568 fn test_update_fee_that_funder_cannot_afford() {
569         let chanmon_cfgs = create_chanmon_cfgs(2);
570         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
571         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
572         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
573         let channel_value = 1888;
574         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000, InitFeatures::known(), InitFeatures::known());
575         let channel_id = chan.2;
576
577         let feerate = 260;
578         nodes[0].node.update_fee(channel_id, feerate).unwrap();
579         check_added_monitors!(nodes[0], 1);
580         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
581
582         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
583
584         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
585
586         //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
587         //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
588         {
589                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
590
591                 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
592                 let num_htlcs = commitment_tx.output.len() - 2;
593                 let total_fee: u64 = feerate as u64 * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
594                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
595                 actual_fee = channel_value - actual_fee;
596                 assert_eq!(total_fee, actual_fee);
597         }
598
599         //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
600         //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
601         nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
602         check_added_monitors!(nodes[0], 1);
603
604         let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
605
606         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap());
607
608         //While producing the commitment_signed response after handling a received update_fee request the
609         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
610         //Should produce and error.
611         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed);
612         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
613         check_added_monitors!(nodes[1], 1);
614         check_closed_broadcast!(nodes[1], true);
615 }
616
617 #[test]
618 fn test_update_fee_with_fundee_update_add_htlc() {
619         let chanmon_cfgs = create_chanmon_cfgs(2);
620         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
621         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
622         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
623         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
624         let channel_id = chan.2;
625         let logger = test_utils::TestLogger::new();
626
627         // balancing
628         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
629
630         let feerate = get_feerate!(nodes[0], channel_id);
631         nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
632         check_added_monitors!(nodes[0], 1);
633
634         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
635         assert_eq!(events_0.len(), 1);
636         let (update_msg, commitment_signed) = match events_0[0] {
637                         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 } } => {
638                         (update_fee.as_ref(), commitment_signed)
639                 },
640                 _ => panic!("Unexpected event"),
641         };
642         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
643         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
644         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
645         check_added_monitors!(nodes[1], 1);
646
647         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
648         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
649         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();
650
651         // nothing happens since node[1] is in AwaitingRemoteRevoke
652         nodes[1].node.send_payment(&route, our_payment_hash, &None).unwrap();
653         {
654                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
655                 assert_eq!(added_monitors.len(), 0);
656                 added_monitors.clear();
657         }
658         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
659         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
660         // node[1] has nothing to do
661
662         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
663         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
664         check_added_monitors!(nodes[0], 1);
665
666         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
667         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
668         // No commitment_signed so get_event_msg's assert(len == 1) passes
669         check_added_monitors!(nodes[0], 1);
670         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
671         check_added_monitors!(nodes[1], 1);
672         // AwaitingRemoteRevoke ends here
673
674         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
675         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
676         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
677         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
678         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
679         assert_eq!(commitment_update.update_fee.is_none(), true);
680
681         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
682         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
683         check_added_monitors!(nodes[0], 1);
684         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
685
686         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
687         check_added_monitors!(nodes[1], 1);
688         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
689
690         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
691         check_added_monitors!(nodes[1], 1);
692         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
693         // No commitment_signed so get_event_msg's assert(len == 1) passes
694
695         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
696         check_added_monitors!(nodes[0], 1);
697         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
698
699         expect_pending_htlcs_forwardable!(nodes[0]);
700
701         let events = nodes[0].node.get_and_clear_pending_events();
702         assert_eq!(events.len(), 1);
703         match events[0] {
704                 Event::PaymentReceived { .. } => { },
705                 _ => panic!("Unexpected event"),
706         };
707
708         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage, 800_000);
709
710         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000, 800_000);
711         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000, 800_000);
712         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
713 }
714
715 #[test]
716 fn test_update_fee() {
717         let chanmon_cfgs = create_chanmon_cfgs(2);
718         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
719         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
720         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
721         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
722         let channel_id = chan.2;
723
724         // A                                        B
725         // (1) update_fee/commitment_signed      ->
726         //                                       <- (2) revoke_and_ack
727         //                                       .- send (3) commitment_signed
728         // (4) update_fee/commitment_signed      ->
729         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
730         //                                       <- (3) commitment_signed delivered
731         // send (6) revoke_and_ack               -.
732         //                                       <- (5) deliver revoke_and_ack
733         // (6) deliver revoke_and_ack            ->
734         //                                       .- send (7) commitment_signed in response to (4)
735         //                                       <- (7) deliver commitment_signed
736         // revoke_and_ack                        ->
737
738         // Create and deliver (1)...
739         let feerate = get_feerate!(nodes[0], channel_id);
740         nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
741         check_added_monitors!(nodes[0], 1);
742
743         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
744         assert_eq!(events_0.len(), 1);
745         let (update_msg, commitment_signed) = match events_0[0] {
746                         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 } } => {
747                         (update_fee.as_ref(), commitment_signed)
748                 },
749                 _ => panic!("Unexpected event"),
750         };
751         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
752
753         // Generate (2) and (3):
754         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
755         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
756         check_added_monitors!(nodes[1], 1);
757
758         // Deliver (2):
759         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
760         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
761         check_added_monitors!(nodes[0], 1);
762
763         // Create and deliver (4)...
764         nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
765         check_added_monitors!(nodes[0], 1);
766         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
767         assert_eq!(events_0.len(), 1);
768         let (update_msg, commitment_signed) = match events_0[0] {
769                         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 } } => {
770                         (update_fee.as_ref(), commitment_signed)
771                 },
772                 _ => panic!("Unexpected event"),
773         };
774
775         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
776         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
777         check_added_monitors!(nodes[1], 1);
778         // ... creating (5)
779         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
780         // No commitment_signed so get_event_msg's assert(len == 1) passes
781
782         // Handle (3), creating (6):
783         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
784         check_added_monitors!(nodes[0], 1);
785         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
786         // No commitment_signed so get_event_msg's assert(len == 1) passes
787
788         // Deliver (5):
789         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
790         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
791         check_added_monitors!(nodes[0], 1);
792
793         // Deliver (6), creating (7):
794         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
795         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
796         assert!(commitment_update.update_add_htlcs.is_empty());
797         assert!(commitment_update.update_fulfill_htlcs.is_empty());
798         assert!(commitment_update.update_fail_htlcs.is_empty());
799         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
800         assert!(commitment_update.update_fee.is_none());
801         check_added_monitors!(nodes[1], 1);
802
803         // Deliver (7)
804         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
805         check_added_monitors!(nodes[0], 1);
806         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
807         // No commitment_signed so get_event_msg's assert(len == 1) passes
808
809         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
810         check_added_monitors!(nodes[1], 1);
811         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
812
813         assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
814         assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
815         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
816 }
817
818 #[test]
819 fn pre_funding_lock_shutdown_test() {
820         // Test sending a shutdown prior to funding_locked after funding generation
821         let chanmon_cfgs = create_chanmon_cfgs(2);
822         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
823         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
824         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
825         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0, InitFeatures::known(), InitFeatures::known());
826         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
827         connect_block(&nodes[0], &Block { header, txdata: vec![tx.clone()]}, 1);
828         connect_block(&nodes[1], &Block { header, txdata: vec![tx.clone()]}, 1);
829
830         nodes[0].node.close_channel(&OutPoint { txid: tx.txid(), index: 0 }.to_channel_id()).unwrap();
831         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
832         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
833         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
834         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
835
836         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
837         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
838         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
839         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
840         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
841         assert!(node_0_none.is_none());
842
843         assert!(nodes[0].node.list_channels().is_empty());
844         assert!(nodes[1].node.list_channels().is_empty());
845 }
846
847 #[test]
848 fn updates_shutdown_wait() {
849         // Test sending a shutdown with outstanding updates pending
850         let chanmon_cfgs = create_chanmon_cfgs(3);
851         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
852         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
853         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
854         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
855         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
856         let logger = test_utils::TestLogger::new();
857
858         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
859
860         nodes[0].node.close_channel(&chan_1.2).unwrap();
861         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
862         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
863         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
864         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
865
866         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
867         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
868
869         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
870
871         let net_graph_msg_handler0 = &nodes[0].net_graph_msg_handler;
872         let net_graph_msg_handler1 = &nodes[1].net_graph_msg_handler;
873         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();
874         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();
875         unwrap_send_err!(nodes[0].node.send_payment(&route_1, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
876         unwrap_send_err!(nodes[1].node.send_payment(&route_2, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
877
878         assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
879         check_added_monitors!(nodes[2], 1);
880         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
881         assert!(updates.update_add_htlcs.is_empty());
882         assert!(updates.update_fail_htlcs.is_empty());
883         assert!(updates.update_fail_malformed_htlcs.is_empty());
884         assert!(updates.update_fee.is_none());
885         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
886         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
887         check_added_monitors!(nodes[1], 1);
888         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
889         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
890
891         assert!(updates_2.update_add_htlcs.is_empty());
892         assert!(updates_2.update_fail_htlcs.is_empty());
893         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
894         assert!(updates_2.update_fee.is_none());
895         assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
896         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
897         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
898
899         let events = nodes[0].node.get_and_clear_pending_events();
900         assert_eq!(events.len(), 1);
901         match events[0] {
902                 Event::PaymentSent { ref payment_preimage } => {
903                         assert_eq!(our_payment_preimage, *payment_preimage);
904                 },
905                 _ => panic!("Unexpected event"),
906         }
907
908         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
909         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
910         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
911         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
912         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
913         assert!(node_0_none.is_none());
914
915         assert!(nodes[0].node.list_channels().is_empty());
916
917         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
918         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
919         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
920         assert!(nodes[1].node.list_channels().is_empty());
921         assert!(nodes[2].node.list_channels().is_empty());
922 }
923
924 #[test]
925 fn htlc_fail_async_shutdown() {
926         // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
927         let chanmon_cfgs = create_chanmon_cfgs(3);
928         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
929         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
930         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
931         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
932         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
933         let logger = test_utils::TestLogger::new();
934
935         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
936         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
937         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();
938         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
939         check_added_monitors!(nodes[0], 1);
940         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
941         assert_eq!(updates.update_add_htlcs.len(), 1);
942         assert!(updates.update_fulfill_htlcs.is_empty());
943         assert!(updates.update_fail_htlcs.is_empty());
944         assert!(updates.update_fail_malformed_htlcs.is_empty());
945         assert!(updates.update_fee.is_none());
946
947         nodes[1].node.close_channel(&chan_1.2).unwrap();
948         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
949         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
950         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
951
952         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
953         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
954         check_added_monitors!(nodes[1], 1);
955         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
956         commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
957
958         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
959         assert!(updates_2.update_add_htlcs.is_empty());
960         assert!(updates_2.update_fulfill_htlcs.is_empty());
961         assert_eq!(updates_2.update_fail_htlcs.len(), 1);
962         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
963         assert!(updates_2.update_fee.is_none());
964
965         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]);
966         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
967
968         expect_payment_failed!(nodes[0], our_payment_hash, false);
969
970         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
971         assert_eq!(msg_events.len(), 2);
972         let node_0_closing_signed = match msg_events[0] {
973                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
974                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
975                         (*msg).clone()
976                 },
977                 _ => panic!("Unexpected event"),
978         };
979         match msg_events[1] {
980                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
981                         assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
982                 },
983                 _ => panic!("Unexpected event"),
984         }
985
986         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
987         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
988         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
989         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
990         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
991         assert!(node_0_none.is_none());
992
993         assert!(nodes[0].node.list_channels().is_empty());
994
995         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
996         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
997         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
998         assert!(nodes[1].node.list_channels().is_empty());
999         assert!(nodes[2].node.list_channels().is_empty());
1000 }
1001
1002 fn do_test_shutdown_rebroadcast(recv_count: u8) {
1003         // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
1004         // messages delivered prior to disconnect
1005         let chanmon_cfgs = create_chanmon_cfgs(3);
1006         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1007         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1008         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1009         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1010         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1011
1012         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
1013
1014         nodes[1].node.close_channel(&chan_1.2).unwrap();
1015         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1016         if recv_count > 0 {
1017                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
1018                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1019                 if recv_count > 1 {
1020                         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
1021                 }
1022         }
1023
1024         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1025         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1026
1027         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1028         let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1029         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1030         let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1031
1032         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish);
1033         let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1034         assert!(node_1_shutdown == node_1_2nd_shutdown);
1035
1036         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish);
1037         let node_0_2nd_shutdown = if recv_count > 0 {
1038                 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1039                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
1040                 node_0_2nd_shutdown
1041         } else {
1042                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1043                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
1044                 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
1045         };
1046         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown);
1047
1048         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1049         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1050
1051         assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
1052         check_added_monitors!(nodes[2], 1);
1053         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1054         assert!(updates.update_add_htlcs.is_empty());
1055         assert!(updates.update_fail_htlcs.is_empty());
1056         assert!(updates.update_fail_malformed_htlcs.is_empty());
1057         assert!(updates.update_fee.is_none());
1058         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
1059         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
1060         check_added_monitors!(nodes[1], 1);
1061         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1062         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
1063
1064         assert!(updates_2.update_add_htlcs.is_empty());
1065         assert!(updates_2.update_fail_htlcs.is_empty());
1066         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
1067         assert!(updates_2.update_fee.is_none());
1068         assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
1069         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
1070         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
1071
1072         let events = nodes[0].node.get_and_clear_pending_events();
1073         assert_eq!(events.len(), 1);
1074         match events[0] {
1075                 Event::PaymentSent { ref payment_preimage } => {
1076                         assert_eq!(our_payment_preimage, *payment_preimage);
1077                 },
1078                 _ => panic!("Unexpected event"),
1079         }
1080
1081         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1082         if recv_count > 0 {
1083                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
1084                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1085                 assert!(node_1_closing_signed.is_some());
1086         }
1087
1088         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1089         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1090
1091         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1092         let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1093         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1094         if recv_count == 0 {
1095                 // If all closing_signeds weren't delivered we can just resume where we left off...
1096                 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1097
1098                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish);
1099                 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1100                 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
1101
1102                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1103                 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1104                 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
1105
1106                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown);
1107                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1108
1109                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown);
1110                 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1111                 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
1112
1113                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed);
1114                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1115                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
1116                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1117                 assert!(node_0_none.is_none());
1118         } else {
1119                 // If one node, however, received + responded with an identical closing_signed we end
1120                 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
1121                 // There isn't really anything better we can do simply, but in the future we might
1122                 // explore storing a set of recently-closed channels that got disconnected during
1123                 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
1124                 // give our counterparty enough time to (potentially) broadcast a cooperative closing
1125                 // transaction.
1126                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1127
1128                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1129                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1130                 assert_eq!(msg_events.len(), 1);
1131                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
1132                         match action {
1133                                 &ErrorAction::SendErrorMessage { ref msg } => {
1134                                         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
1135                                         assert_eq!(msg.channel_id, chan_1.2);
1136                                 },
1137                                 _ => panic!("Unexpected event!"),
1138                         }
1139                 } else { panic!("Needed SendErrorMessage close"); }
1140
1141                 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
1142                 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
1143                 // closing_signed so we do it ourselves
1144                 check_closed_broadcast!(nodes[0], false);
1145                 check_added_monitors!(nodes[0], 1);
1146         }
1147
1148         assert!(nodes[0].node.list_channels().is_empty());
1149
1150         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1151         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1152         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1153         assert!(nodes[1].node.list_channels().is_empty());
1154         assert!(nodes[2].node.list_channels().is_empty());
1155 }
1156
1157 #[test]
1158 fn test_shutdown_rebroadcast() {
1159         do_test_shutdown_rebroadcast(0);
1160         do_test_shutdown_rebroadcast(1);
1161         do_test_shutdown_rebroadcast(2);
1162 }
1163
1164 #[test]
1165 fn fake_network_test() {
1166         // Simple test which builds a network of ChannelManagers, connects them to each other, and
1167         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
1168         let chanmon_cfgs = create_chanmon_cfgs(4);
1169         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1170         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1171         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1172
1173         // Create some initial channels
1174         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1175         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1176         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1177
1178         // Rebalance the network a bit by relaying one payment through all the channels...
1179         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1180         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1181         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1182         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1183
1184         // Send some more payments
1185         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000, 1_000_000);
1186         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000, 1_000_000);
1187         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000, 1_000_000);
1188
1189         // Test failure packets
1190         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1191         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1192
1193         // Add a new channel that skips 3
1194         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1195
1196         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000, 1_000_000);
1197         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000, 1_000_000);
1198         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1199         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1200         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1201         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1202         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1203
1204         // Do some rebalance loop payments, simultaneously
1205         let mut hops = Vec::with_capacity(3);
1206         hops.push(RouteHop {
1207                 pubkey: nodes[2].node.get_our_node_id(),
1208                 node_features: NodeFeatures::empty(),
1209                 short_channel_id: chan_2.0.contents.short_channel_id,
1210                 channel_features: ChannelFeatures::empty(),
1211                 fee_msat: 0,
1212                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1213         });
1214         hops.push(RouteHop {
1215                 pubkey: nodes[3].node.get_our_node_id(),
1216                 node_features: NodeFeatures::empty(),
1217                 short_channel_id: chan_3.0.contents.short_channel_id,
1218                 channel_features: ChannelFeatures::empty(),
1219                 fee_msat: 0,
1220                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1221         });
1222         hops.push(RouteHop {
1223                 pubkey: nodes[1].node.get_our_node_id(),
1224                 node_features: NodeFeatures::empty(),
1225                 short_channel_id: chan_4.0.contents.short_channel_id,
1226                 channel_features: ChannelFeatures::empty(),
1227                 fee_msat: 1000000,
1228                 cltv_expiry_delta: TEST_FINAL_CLTV,
1229         });
1230         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;
1231         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;
1232         let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1233
1234         let mut hops = Vec::with_capacity(3);
1235         hops.push(RouteHop {
1236                 pubkey: nodes[3].node.get_our_node_id(),
1237                 node_features: NodeFeatures::empty(),
1238                 short_channel_id: chan_4.0.contents.short_channel_id,
1239                 channel_features: ChannelFeatures::empty(),
1240                 fee_msat: 0,
1241                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1242         });
1243         hops.push(RouteHop {
1244                 pubkey: nodes[2].node.get_our_node_id(),
1245                 node_features: NodeFeatures::empty(),
1246                 short_channel_id: chan_3.0.contents.short_channel_id,
1247                 channel_features: ChannelFeatures::empty(),
1248                 fee_msat: 0,
1249                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1250         });
1251         hops.push(RouteHop {
1252                 pubkey: nodes[1].node.get_our_node_id(),
1253                 node_features: NodeFeatures::empty(),
1254                 short_channel_id: chan_2.0.contents.short_channel_id,
1255                 channel_features: ChannelFeatures::empty(),
1256                 fee_msat: 1000000,
1257                 cltv_expiry_delta: TEST_FINAL_CLTV,
1258         });
1259         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;
1260         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;
1261         let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1262
1263         // Claim the rebalances...
1264         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1265         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1, 1_000_000);
1266
1267         // Add a duplicate new channel from 2 to 4
1268         let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1269
1270         // Send some payments across both channels
1271         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1272         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1273         let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1274
1275
1276         route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1277         let events = nodes[0].node.get_and_clear_pending_msg_events();
1278         assert_eq!(events.len(), 0);
1279         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);
1280
1281         //TODO: Test that routes work again here as we've been notified that the channel is full
1282
1283         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3, 3_000_000);
1284         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4, 3_000_000);
1285         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5, 3_000_000);
1286
1287         // Close down the channels...
1288         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1289         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1290         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1291         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1292         close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1293 }
1294
1295 #[test]
1296 fn holding_cell_htlc_counting() {
1297         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1298         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1299         // commitment dance rounds.
1300         let chanmon_cfgs = create_chanmon_cfgs(3);
1301         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1302         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1303         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1304         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1305         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1306         let logger = test_utils::TestLogger::new();
1307
1308         let mut payments = Vec::new();
1309         for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1310                 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1311                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1312                 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();
1313                 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
1314                 payments.push((payment_preimage, payment_hash));
1315         }
1316         check_added_monitors!(nodes[1], 1);
1317
1318         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1319         assert_eq!(events.len(), 1);
1320         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1321         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1322
1323         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1324         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1325         // another HTLC.
1326         let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
1327         {
1328                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1329                 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();
1330                 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &None), true, APIError::ChannelUnavailable { ref err },
1331                         assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1332                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1333                 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1334         }
1335
1336         // This should also be true if we try to forward a payment.
1337         let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
1338         {
1339                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1340                 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();
1341                 nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
1342                 check_added_monitors!(nodes[0], 1);
1343         }
1344
1345         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1346         assert_eq!(events.len(), 1);
1347         let payment_event = SendEvent::from_event(events.pop().unwrap());
1348         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1349
1350         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1351         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1352         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1353         // fails), the second will process the resulting failure and fail the HTLC backward.
1354         expect_pending_htlcs_forwardable!(nodes[1]);
1355         expect_pending_htlcs_forwardable!(nodes[1]);
1356         check_added_monitors!(nodes[1], 1);
1357
1358         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1359         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1360         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1361
1362         let events = nodes[0].node.get_and_clear_pending_msg_events();
1363         assert_eq!(events.len(), 1);
1364         match events[0] {
1365                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
1366                         assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
1367                 },
1368                 _ => panic!("Unexpected event"),
1369         }
1370
1371         expect_payment_failed!(nodes[0], payment_hash_2, false);
1372
1373         // Now forward all the pending HTLCs and claim them back
1374         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1375         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1376         check_added_monitors!(nodes[2], 1);
1377
1378         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1379         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1380         check_added_monitors!(nodes[1], 1);
1381         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1382
1383         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1384         check_added_monitors!(nodes[1], 1);
1385         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1386
1387         for ref update in as_updates.update_add_htlcs.iter() {
1388                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1389         }
1390         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1391         check_added_monitors!(nodes[2], 1);
1392         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1393         check_added_monitors!(nodes[2], 1);
1394         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1395
1396         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1397         check_added_monitors!(nodes[1], 1);
1398         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1399         check_added_monitors!(nodes[1], 1);
1400         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1401
1402         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1403         check_added_monitors!(nodes[2], 1);
1404
1405         expect_pending_htlcs_forwardable!(nodes[2]);
1406
1407         let events = nodes[2].node.get_and_clear_pending_events();
1408         assert_eq!(events.len(), payments.len());
1409         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1410                 match event {
1411                         &Event::PaymentReceived { ref payment_hash, .. } => {
1412                                 assert_eq!(*payment_hash, *hash);
1413                         },
1414                         _ => panic!("Unexpected event"),
1415                 };
1416         }
1417
1418         for (preimage, _) in payments.drain(..) {
1419                 claim_payment(&nodes[1], &[&nodes[2]], preimage, 100_000);
1420         }
1421
1422         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000, 1_000_000);
1423 }
1424
1425 #[test]
1426 fn duplicate_htlc_test() {
1427         // Test that we accept duplicate payment_hash HTLCs across the network and that
1428         // claiming/failing them are all separate and don't affect each other
1429         let chanmon_cfgs = create_chanmon_cfgs(6);
1430         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1431         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1432         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1433
1434         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1435         create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1436         create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1437         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1438         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1439         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1440
1441         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1442
1443         *nodes[0].network_payment_count.borrow_mut() -= 1;
1444         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1445
1446         *nodes[0].network_payment_count.borrow_mut() -= 1;
1447         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1448
1449         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage, 1_000_000);
1450         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1451         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage, 1_000_000);
1452 }
1453
1454 #[test]
1455 fn test_duplicate_htlc_different_direction_onchain() {
1456         // Test that ChannelMonitor doesn't generate 2 preimage txn
1457         // when we have 2 HTLCs with same preimage that go across a node
1458         // in opposite directions.
1459         let chanmon_cfgs = create_chanmon_cfgs(2);
1460         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1461         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1462         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1463
1464         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1465         let logger = test_utils::TestLogger::new();
1466
1467         // balancing
1468         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
1469
1470         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1471
1472         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1473         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();
1474         send_along_route_with_hash(&nodes[1], route, &vec!(&nodes[0])[..], 800_000, payment_hash);
1475
1476         // Provide preimage to node 0 by claiming payment
1477         nodes[0].node.claim_funds(payment_preimage, &None, 800_000);
1478         check_added_monitors!(nodes[0], 1);
1479
1480         // Broadcast node 1 commitment txn
1481         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1482
1483         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1484         let mut has_both_htlcs = 0; // check htlcs match ones committed
1485         for outp in remote_txn[0].output.iter() {
1486                 if outp.value == 800_000 / 1000 {
1487                         has_both_htlcs += 1;
1488                 } else if outp.value == 900_000 / 1000 {
1489                         has_both_htlcs += 1;
1490                 }
1491         }
1492         assert_eq!(has_both_htlcs, 2);
1493
1494         let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1495         connect_block(&nodes[0], &Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
1496         check_added_monitors!(nodes[0], 1);
1497
1498         // Check we only broadcast 1 timeout tx
1499         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1500         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()) };
1501         assert_eq!(claim_txn.len(), 5);
1502         check_spends!(claim_txn[2], chan_1.3);
1503         check_spends!(claim_txn[3], claim_txn[2]);
1504         assert_eq!(htlc_pair.0.input.len(), 1);
1505         assert_eq!(htlc_pair.0.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1506         check_spends!(htlc_pair.0, remote_txn[0]);
1507         assert_eq!(htlc_pair.1.input.len(), 1);
1508         assert_eq!(htlc_pair.1.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1509         check_spends!(htlc_pair.1, remote_txn[0]);
1510
1511         let events = nodes[0].node.get_and_clear_pending_msg_events();
1512         assert_eq!(events.len(), 2);
1513         for e in events {
1514                 match e {
1515                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1516                         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, .. } } => {
1517                                 assert!(update_add_htlcs.is_empty());
1518                                 assert!(update_fail_htlcs.is_empty());
1519                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1520                                 assert!(update_fail_malformed_htlcs.is_empty());
1521                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1522                         },
1523                         _ => panic!("Unexpected event"),
1524                 }
1525         }
1526 }
1527
1528 #[test]
1529 fn test_basic_channel_reserve() {
1530         let chanmon_cfgs = create_chanmon_cfgs(2);
1531         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1532         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1533         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1534         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1535         let logger = test_utils::TestLogger::new();
1536
1537         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1538         let channel_reserve = chan_stat.channel_reserve_msat;
1539
1540         // The 2* and +1 are for the fee spike reserve.
1541         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
1542         let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1);
1543         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1544         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1545         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();
1546         let err = nodes[0].node.send_payment(&route, our_payment_hash, &None).err().unwrap();
1547         match err {
1548                 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1549                         match &fails[0] {
1550                                 &APIError::ChannelUnavailable{ref err} =>
1551                                         assert!(regex::Regex::new(r"Cannot send value that would put us under local channel reserve value \(\d+\)").unwrap().is_match(err)),
1552                                 _ => panic!("Unexpected error variant"),
1553                         }
1554                 },
1555                 _ => panic!("Unexpected error variant"),
1556         }
1557         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1558         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us under local channel reserve value".to_string(), 1);
1559
1560         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send, max_can_send);
1561 }
1562
1563 #[test]
1564 fn test_fee_spike_violation_fails_htlc() {
1565         let chanmon_cfgs = create_chanmon_cfgs(2);
1566         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1567         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1568         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1569         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1570         let logger = test_utils::TestLogger::new();
1571
1572         macro_rules! get_route_and_payment_hash {
1573                 ($recv_value: expr) => {{
1574                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1575                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler.network_graph.read().unwrap();
1576                         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();
1577                         (route, payment_hash, payment_preimage)
1578                 }}
1579         };
1580
1581         let (route, payment_hash, _) = get_route_and_payment_hash!(3460001);
1582         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1583         let secp_ctx = Secp256k1::new();
1584         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1585
1586         let cur_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1587
1588         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1589         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &None, cur_height).unwrap();
1590         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1591         let msg = msgs::UpdateAddHTLC {
1592                 channel_id: chan.2,
1593                 htlc_id: 0,
1594                 amount_msat: htlc_msat,
1595                 payment_hash: payment_hash,
1596                 cltv_expiry: htlc_cltv,
1597                 onion_routing_packet: onion_packet,
1598         };
1599
1600         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1601
1602         // Now manually create the commitment_signed message corresponding to the update_add
1603         // nodes[0] just sent. In the code for construction of this message, "local" refers
1604         // to the sender of the message, and "remote" refers to the receiver.
1605
1606         let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1607
1608         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1609
1610         // Get the EnforcingChannelKeys for each channel, which will be used to (1) get the keys
1611         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1612         let (local_revocation_basepoint, local_htlc_basepoint, local_payment_point, local_secret, local_secret2) = {
1613                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1614                 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1615                 let chan_keys = local_chan.get_local_keys();
1616                 let pubkeys = chan_keys.pubkeys();
1617                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint, pubkeys.payment_point,
1618                  chan_keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER), chan_keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2))
1619         };
1620         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_payment_point, remote_secret1) = {
1621                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1622                 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1623                 let chan_keys = remote_chan.get_local_keys();
1624                 let pubkeys = chan_keys.pubkeys();
1625                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint, pubkeys.payment_point,
1626                  chan_keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1))
1627         };
1628
1629         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1630         let commitment_secret = SecretKey::from_slice(&remote_secret1).unwrap();
1631         let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &commitment_secret);
1632         let commit_tx_keys = chan_utils::TxCreationKeys::new(&secp_ctx, &per_commitment_point, &remote_delayed_payment_basepoint,
1633                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1634
1635         // Build the remote commitment transaction so we can sign it, and then later use the
1636         // signature for the commitment_signed message.
1637         let local_chan_balance = 1313;
1638         let static_payment_pk = local_payment_point.serialize();
1639         let remote_commit_tx_output = TxOut {
1640                                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0)
1641                                                              .push_slice(&WPubkeyHash::hash(&static_payment_pk)[..])
1642                                                              .into_script(),
1643                 value: local_chan_balance as u64
1644         };
1645
1646         let local_commit_tx_output = TxOut {
1647                 script_pubkey: chan_utils::get_revokeable_redeemscript(&commit_tx_keys.revocation_key,
1648                                                                                BREAKDOWN_TIMEOUT,
1649                                                                                &commit_tx_keys.a_delayed_payment_key).to_v0_p2wsh(),
1650                                 value: 95000,
1651         };
1652
1653         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1654                 offered: false,
1655                 amount_msat: 3460001,
1656                 cltv_expiry: htlc_cltv,
1657                 payment_hash: payment_hash,
1658                 transaction_output_index: Some(1),
1659         };
1660
1661         let htlc_output = TxOut {
1662                 script_pubkey: chan_utils::get_htlc_redeemscript(&accepted_htlc_info, &commit_tx_keys).to_v0_p2wsh(),
1663                 value: 3460001 / 1000
1664         };
1665
1666         let commit_tx_obscure_factor = {
1667                 let mut sha = Sha256::engine();
1668                 let remote_payment_point = &remote_payment_point.serialize();
1669                 sha.input(&local_payment_point.serialize());
1670                 sha.input(remote_payment_point);
1671                 let res = Sha256::from_engine(sha).into_inner();
1672
1673                 ((res[26] as u64) << 5*8) |
1674                 ((res[27] as u64) << 4*8) |
1675                 ((res[28] as u64) << 3*8) |
1676                 ((res[29] as u64) << 2*8) |
1677                 ((res[30] as u64) << 1*8) |
1678                 ((res[31] as u64) << 0*8)
1679         };
1680         let commitment_number = 1;
1681         let obscured_commitment_transaction_number = commit_tx_obscure_factor ^ commitment_number;
1682         let lock_time = ((0x20 as u32) << 8*3) | ((obscured_commitment_transaction_number & 0xffffffu64) as u32);
1683         let input = TxIn {
1684                 previous_output: BitcoinOutPoint { txid: chan.3.txid(), vout: 0 },
1685                 script_sig: Script::new(),
1686                 sequence: ((0x80 as u32) << 8*3) | ((obscured_commitment_transaction_number >> 3*8) as u32),
1687                 witness: Vec::new(),
1688         };
1689
1690         let commit_tx = Transaction {
1691                 version: 2,
1692                 lock_time,
1693                 input: vec![input],
1694                 output: vec![remote_commit_tx_output, htlc_output, local_commit_tx_output],
1695         };
1696         let res = {
1697                 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1698                 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1699                 let local_chan_keys = local_chan.get_local_keys();
1700                 local_chan_keys.sign_remote_commitment(feerate_per_kw, &commit_tx, &commit_tx_keys, &[&accepted_htlc_info], &secp_ctx).unwrap()
1701         };
1702
1703         let commit_signed_msg = msgs::CommitmentSigned {
1704                 channel_id: chan.2,
1705                 signature: res.0,
1706                 htlc_signatures: res.1
1707         };
1708
1709         // Send the commitment_signed message to the nodes[1].
1710         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1711         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1712
1713         // Send the RAA to nodes[1].
1714         let per_commitment_secret = local_secret;
1715         let next_secret = SecretKey::from_slice(&local_secret2).unwrap();
1716         let next_per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &next_secret);
1717         let raa_msg = msgs::RevokeAndACK{ channel_id: chan.2, per_commitment_secret, next_per_commitment_point};
1718         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1719
1720         let events = nodes[1].node.get_and_clear_pending_msg_events();
1721         assert_eq!(events.len(), 1);
1722         // Make sure the HTLC failed in the way we expect.
1723         match events[0] {
1724                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1725                         assert_eq!(update_fail_htlcs.len(), 1);
1726                         update_fail_htlcs[0].clone()
1727                 },
1728                 _ => panic!("Unexpected event"),
1729         };
1730         nodes[1].logger.assert_log("lightning::ln::channel".to_string(), "Attempting to fail HTLC due to fee spike buffer violation".to_string(), 1);
1731
1732         check_added_monitors!(nodes[1], 2);
1733 }
1734
1735 #[test]
1736 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1737         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1738         // Set the fee rate for the channel very high, to the point where the fundee
1739         // sending any amount would result in a channel reserve violation. In this test
1740         // we check that we would be prevented from sending an HTLC in this situation.
1741         chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1742         chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1743         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1744         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1745         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1746         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1747         let logger = test_utils::TestLogger::new();
1748
1749         macro_rules! get_route_and_payment_hash {
1750                 ($recv_value: expr) => {{
1751                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1752                         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1753                         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();
1754                         (route, payment_hash, payment_preimage)
1755                 }}
1756         };
1757
1758         let (route, our_payment_hash, _) = get_route_and_payment_hash!(1000);
1759         unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1760                 assert_eq!(err, "Cannot send value that would put them under remote channel reserve value"));
1761         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1762         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put them under remote channel reserve value".to_string(), 1);
1763 }
1764
1765 #[test]
1766 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1767         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1768         // Set the fee rate for the channel very high, to the point where the funder
1769         // receiving 1 update_add_htlc would result in them closing the channel due
1770         // to channel reserve violation. This close could also happen if the fee went
1771         // up a more realistic amount, but many HTLCs were outstanding at the time of
1772         // the update_add_htlc.
1773         chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1774         chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1775         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1776         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1777         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1778         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1779         let logger = test_utils::TestLogger::new();
1780
1781         macro_rules! get_route_and_payment_hash {
1782                 ($recv_value: expr) => {{
1783                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1784                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1785                         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();
1786                         (route, payment_hash, payment_preimage)
1787                 }}
1788         };
1789
1790         let (route, payment_hash, _) = get_route_and_payment_hash!(1000);
1791         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1792         let secp_ctx = Secp256k1::new();
1793         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1794         let cur_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1795         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1796         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 1000, &None, cur_height).unwrap();
1797         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1798         let msg = msgs::UpdateAddHTLC {
1799                 channel_id: chan.2,
1800                 htlc_id: 1,
1801                 amount_msat: htlc_msat + 1,
1802                 payment_hash: payment_hash,
1803                 cltv_expiry: htlc_cltv,
1804                 onion_routing_packet: onion_packet,
1805         };
1806
1807         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1808         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1809         nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot receive value that would put us under local channel reserve value".to_string(), 1);
1810         assert_eq!(nodes[0].node.list_channels().len(), 0);
1811         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1812         assert_eq!(err_msg.data, "Cannot receive value that would put us under local channel reserve value");
1813         check_added_monitors!(nodes[0], 1);
1814 }
1815
1816 #[test]
1817 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1818         let chanmon_cfgs = create_chanmon_cfgs(3);
1819         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1820         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1821         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1822         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1823         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1824         let logger = test_utils::TestLogger::new();
1825
1826         macro_rules! get_route_and_payment_hash {
1827                 ($recv_value: expr) => {{
1828                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1829                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1830                         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();
1831                         (route, payment_hash, payment_preimage)
1832                 }}
1833         };
1834
1835         let feemsat = 239;
1836         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1837         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1838         let feerate = get_feerate!(nodes[0], chan.2);
1839
1840         // Add a 2* and +1 for the fee spike reserve.
1841         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1);
1842         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;
1843         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1844
1845         // Add a pending HTLC.
1846         let (route_1, our_payment_hash_1, _) = get_route_and_payment_hash!(amt_msat_1);
1847         let payment_event_1 = {
1848                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
1849                 check_added_monitors!(nodes[0], 1);
1850
1851                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1852                 assert_eq!(events.len(), 1);
1853                 SendEvent::from_event(events.remove(0))
1854         };
1855         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1856
1857         // Attempt to trigger a channel reserve violation --> payment failure.
1858         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2);
1859         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;
1860         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1861         let (route_2, _, _) = get_route_and_payment_hash!(amt_msat_2);
1862
1863         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1864         let secp_ctx = Secp256k1::new();
1865         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1866         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1867         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1868         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height).unwrap();
1869         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1870         let msg = msgs::UpdateAddHTLC {
1871                 channel_id: chan.2,
1872                 htlc_id: 1,
1873                 amount_msat: htlc_msat + 1,
1874                 payment_hash: our_payment_hash_1,
1875                 cltv_expiry: htlc_cltv,
1876                 onion_routing_packet: onion_packet,
1877         };
1878
1879         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1880         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1881         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1882         assert_eq!(nodes[1].node.list_channels().len(), 1);
1883         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1884         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1885         check_added_monitors!(nodes[1], 1);
1886 }
1887
1888 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64) -> u64 {
1889         (COMMITMENT_TX_BASE_WEIGHT + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1890 }
1891
1892 #[test]
1893 fn test_channel_reserve_holding_cell_htlcs() {
1894         let chanmon_cfgs = create_chanmon_cfgs(3);
1895         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1896         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1897         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1898         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1899         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1900         let logger = test_utils::TestLogger::new();
1901
1902         let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1903         let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1904
1905         let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1906         let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1907
1908         macro_rules! get_route_and_payment_hash {
1909                 ($recv_value: expr) => {{
1910                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1911                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1912                         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();
1913                         (route, payment_hash, payment_preimage)
1914                 }}
1915         };
1916
1917         macro_rules! expect_forward {
1918                 ($node: expr) => {{
1919                         let mut events = $node.node.get_and_clear_pending_msg_events();
1920                         assert_eq!(events.len(), 1);
1921                         check_added_monitors!($node, 1);
1922                         let payment_event = SendEvent::from_event(events.remove(0));
1923                         payment_event
1924                 }}
1925         }
1926
1927         let feemsat = 239; // somehow we know?
1928         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1929         let feerate = get_feerate!(nodes[0], chan_1.2);
1930
1931         let recv_value_0 = stat01.their_max_htlc_value_in_flight_msat - total_fee_msat;
1932
1933         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1934         {
1935                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
1936                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1937                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1938                         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)));
1939                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1940                 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);
1941         }
1942
1943         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1944         // nodes[0]'s wealth
1945         loop {
1946                 let amt_msat = recv_value_0 + total_fee_msat;
1947                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1948                 // Also, ensure that each payment has enough to be over the dust limit to
1949                 // ensure it'll be included in each commit tx fee calculation.
1950                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1951                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.their_dust_limit_msat + 1000);
1952                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1953                         break;
1954                 }
1955                 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0, recv_value_0);
1956
1957                 let (stat01_, stat11_, stat12_, stat22_) = (
1958                         get_channel_value_stat!(nodes[0], chan_1.2),
1959                         get_channel_value_stat!(nodes[1], chan_1.2),
1960                         get_channel_value_stat!(nodes[1], chan_2.2),
1961                         get_channel_value_stat!(nodes[2], chan_2.2),
1962                 );
1963
1964                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1965                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1966                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1967                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1968                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1969         }
1970
1971         // adding pending output.
1972         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1973         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1974         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1975         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1976         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1977         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1978         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1979         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1980         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1981         // policy.
1982         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1);
1983         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1984         let amt_msat_1 = recv_value_1 + total_fee_msat;
1985
1986         let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
1987         let payment_event_1 = {
1988                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
1989                 check_added_monitors!(nodes[0], 1);
1990
1991                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1992                 assert_eq!(events.len(), 1);
1993                 SendEvent::from_event(events.remove(0))
1994         };
1995         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1996
1997         // channel reserve test with htlc pending output > 0
1998         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1999         {
2000                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
2001                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
2002                         assert!(regex::Regex::new(r"Cannot send value that would put us under local channel reserve value \(\d+\)").unwrap().is_match(err)));
2003                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2004         }
2005
2006         // split the rest to test holding cell
2007         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
2008         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
2009         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
2010         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
2011         {
2012                 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
2013                 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);
2014         }
2015
2016         // now see if they go through on both sides
2017         let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
2018         // but this will stuck in the holding cell
2019         nodes[0].node.send_payment(&route_21, our_payment_hash_21, &None).unwrap();
2020         check_added_monitors!(nodes[0], 0);
2021         let events = nodes[0].node.get_and_clear_pending_events();
2022         assert_eq!(events.len(), 0);
2023
2024         // test with outbound holding cell amount > 0
2025         {
2026                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+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 us under local channel reserve value \(\d+\)").unwrap().is_match(err)));
2029                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2030                 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us under local channel reserve value".to_string(), 2);
2031         }
2032
2033         let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
2034         // this will also stuck in the holding cell
2035         nodes[0].node.send_payment(&route_22, our_payment_hash_22, &None).unwrap();
2036         check_added_monitors!(nodes[0], 0);
2037         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
2038         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2039
2040         // flush the pending htlc
2041         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
2042         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2043         check_added_monitors!(nodes[1], 1);
2044
2045         // the pending htlc should be promoted to committed
2046         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
2047         check_added_monitors!(nodes[0], 1);
2048         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2049
2050         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
2051         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2052         // No commitment_signed so get_event_msg's assert(len == 1) passes
2053         check_added_monitors!(nodes[0], 1);
2054
2055         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
2056         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2057         check_added_monitors!(nodes[1], 1);
2058
2059         expect_pending_htlcs_forwardable!(nodes[1]);
2060
2061         let ref payment_event_11 = expect_forward!(nodes[1]);
2062         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
2063         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
2064
2065         expect_pending_htlcs_forwardable!(nodes[2]);
2066         expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
2067
2068         // flush the htlcs in the holding cell
2069         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
2070         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
2071         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
2072         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
2073         expect_pending_htlcs_forwardable!(nodes[1]);
2074
2075         let ref payment_event_3 = expect_forward!(nodes[1]);
2076         assert_eq!(payment_event_3.msgs.len(), 2);
2077         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
2078         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
2079
2080         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2081         expect_pending_htlcs_forwardable!(nodes[2]);
2082
2083         let events = nodes[2].node.get_and_clear_pending_events();
2084         assert_eq!(events.len(), 2);
2085         match events[0] {
2086                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2087                         assert_eq!(our_payment_hash_21, *payment_hash);
2088                         assert_eq!(*payment_secret, None);
2089                         assert_eq!(recv_value_21, amt);
2090                 },
2091                 _ => panic!("Unexpected event"),
2092         }
2093         match events[1] {
2094                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2095                         assert_eq!(our_payment_hash_22, *payment_hash);
2096                         assert_eq!(None, *payment_secret);
2097                         assert_eq!(recv_value_22, amt);
2098                 },
2099                 _ => panic!("Unexpected event"),
2100         }
2101
2102         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1, recv_value_1);
2103         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21, recv_value_21);
2104         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22, recv_value_22);
2105
2106         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1);
2107         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2108         {
2109                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_3 + 1);
2110                 let err = nodes[0].node.send_payment(&route, our_payment_hash, &None).err().unwrap();
2111                 match err {
2112                         PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
2113                                 match &fails[0] {
2114                                         &APIError::ChannelUnavailable{ref err} =>
2115                                                 assert!(regex::Regex::new(r"Cannot send value that would put us under local channel reserve value \(\d+\)").unwrap().is_match(err)),
2116                                         _ => panic!("Unexpected error variant"),
2117                                 }
2118                         },
2119                         _ => panic!("Unexpected error variant"),
2120                 }
2121                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2122                 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us under local channel reserve value".to_string(), 3);
2123         }
2124
2125         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3, recv_value_3);
2126
2127         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1);
2128         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);
2129         let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2130         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2131         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2132
2133         let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2134         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2135 }
2136
2137 #[test]
2138 fn channel_reserve_in_flight_removes() {
2139         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2140         // can send to its counterparty, but due to update ordering, the other side may not yet have
2141         // considered those HTLCs fully removed.
2142         // This tests that we don't count HTLCs which will not be included in the next remote
2143         // commitment transaction towards the reserve value (as it implies no commitment transaction
2144         // will be generated which violates the remote reserve value).
2145         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2146         // To test this we:
2147         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2148         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2149         //    you only consider the value of the first HTLC, it may not),
2150         //  * start routing a third HTLC from A to B,
2151         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2152         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2153         //  * deliver the first fulfill from B
2154         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2155         //    claim,
2156         //  * deliver A's response CS and RAA.
2157         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2158         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2159         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2160         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2161         let chanmon_cfgs = create_chanmon_cfgs(2);
2162         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2163         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2164         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2165         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2166         let logger = test_utils::TestLogger::new();
2167
2168         let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2169         // Route the first two HTLCs.
2170         let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
2171         let (payment_preimage_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
2172
2173         // Start routing the third HTLC (this is just used to get everyone in the right state).
2174         let (payment_preimage_3, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
2175         let send_1 = {
2176                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
2177                 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();
2178                 nodes[0].node.send_payment(&route, payment_hash_3, &None).unwrap();
2179                 check_added_monitors!(nodes[0], 1);
2180                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2181                 assert_eq!(events.len(), 1);
2182                 SendEvent::from_event(events.remove(0))
2183         };
2184
2185         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2186         // initial fulfill/CS.
2187         assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000));
2188         check_added_monitors!(nodes[1], 1);
2189         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2190
2191         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2192         // remove the second HTLC when we send the HTLC back from B to A.
2193         assert!(nodes[1].node.claim_funds(payment_preimage_2, &None, 20000));
2194         check_added_monitors!(nodes[1], 1);
2195         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2196
2197         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2198         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2199         check_added_monitors!(nodes[0], 1);
2200         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2201         expect_payment_sent!(nodes[0], payment_preimage_1);
2202
2203         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2204         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2205         check_added_monitors!(nodes[1], 1);
2206         // B is already AwaitingRAA, so cant generate a CS here
2207         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2208
2209         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2210         check_added_monitors!(nodes[1], 1);
2211         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2212
2213         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2214         check_added_monitors!(nodes[0], 1);
2215         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2216
2217         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2218         check_added_monitors!(nodes[1], 1);
2219         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2220
2221         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2222         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2223         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2224         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2225         // on-chain as necessary).
2226         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2227         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2228         check_added_monitors!(nodes[0], 1);
2229         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2230         expect_payment_sent!(nodes[0], payment_preimage_2);
2231
2232         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2233         check_added_monitors!(nodes[1], 1);
2234         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2235
2236         expect_pending_htlcs_forwardable!(nodes[1]);
2237         expect_payment_received!(nodes[1], payment_hash_3, 100000);
2238
2239         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2240         // resolve the second HTLC from A's point of view.
2241         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2242         check_added_monitors!(nodes[0], 1);
2243         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2244
2245         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2246         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2247         let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[1]);
2248         let send_2 = {
2249                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
2250                 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();
2251                 nodes[1].node.send_payment(&route, payment_hash_4, &None).unwrap();
2252                 check_added_monitors!(nodes[1], 1);
2253                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2254                 assert_eq!(events.len(), 1);
2255                 SendEvent::from_event(events.remove(0))
2256         };
2257
2258         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2259         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2260         check_added_monitors!(nodes[0], 1);
2261         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2262
2263         // Now just resolve all the outstanding messages/HTLCs for completeness...
2264
2265         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2266         check_added_monitors!(nodes[1], 1);
2267         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2268
2269         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2270         check_added_monitors!(nodes[1], 1);
2271
2272         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2273         check_added_monitors!(nodes[0], 1);
2274         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2275
2276         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2277         check_added_monitors!(nodes[1], 1);
2278         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2279
2280         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2281         check_added_monitors!(nodes[0], 1);
2282
2283         expect_pending_htlcs_forwardable!(nodes[0]);
2284         expect_payment_received!(nodes[0], payment_hash_4, 10000);
2285
2286         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4, 10_000);
2287         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3, 100_000);
2288 }
2289
2290 #[test]
2291 fn channel_monitor_network_test() {
2292         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2293         // tests that ChannelMonitor is able to recover from various states.
2294         let chanmon_cfgs = create_chanmon_cfgs(5);
2295         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2296         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2297         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2298
2299         // Create some initial channels
2300         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2301         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2302         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2303         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2304
2305         // Rebalance the network a bit by relaying one payment through all the channels...
2306         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2307         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2308         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2309         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2310
2311         // Simple case with no pending HTLCs:
2312         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2313         check_added_monitors!(nodes[1], 1);
2314         {
2315                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2316                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2317                 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
2318                 check_added_monitors!(nodes[0], 1);
2319                 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2320         }
2321         get_announce_close_broadcast_events(&nodes, 0, 1);
2322         assert_eq!(nodes[0].node.list_channels().len(), 0);
2323         assert_eq!(nodes[1].node.list_channels().len(), 1);
2324
2325         // One pending HTLC is discarded by the force-close:
2326         let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2327
2328         // Simple case of one pending HTLC to HTLC-Timeout
2329         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2330         check_added_monitors!(nodes[1], 1);
2331         {
2332                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2333                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2334                 connect_block(&nodes[2], &Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
2335                 check_added_monitors!(nodes[2], 1);
2336                 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2337         }
2338         get_announce_close_broadcast_events(&nodes, 1, 2);
2339         assert_eq!(nodes[1].node.list_channels().len(), 0);
2340         assert_eq!(nodes[2].node.list_channels().len(), 1);
2341
2342         macro_rules! claim_funds {
2343                 ($node: expr, $prev_node: expr, $preimage: expr, $amount: expr) => {
2344                         {
2345                                 assert!($node.node.claim_funds($preimage, &None, $amount));
2346                                 check_added_monitors!($node, 1);
2347
2348                                 let events = $node.node.get_and_clear_pending_msg_events();
2349                                 assert_eq!(events.len(), 1);
2350                                 match events[0] {
2351                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2352                                                 assert!(update_add_htlcs.is_empty());
2353                                                 assert!(update_fail_htlcs.is_empty());
2354                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2355                                         },
2356                                         _ => panic!("Unexpected event"),
2357                                 };
2358                         }
2359                 }
2360         }
2361
2362         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2363         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2364         nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2365         check_added_monitors!(nodes[2], 1);
2366         let node2_commitment_txid;
2367         {
2368                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2369                 node2_commitment_txid = node_txn[0].txid();
2370
2371                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2372                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, 3_000_000);
2373
2374                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2375                 connect_block(&nodes[3], &Block { header, txdata: vec![node_txn[0].clone()] }, 1);
2376                 check_added_monitors!(nodes[3], 1);
2377
2378                 check_preimage_claim(&nodes[3], &node_txn);
2379         }
2380         get_announce_close_broadcast_events(&nodes, 2, 3);
2381         assert_eq!(nodes[2].node.list_channels().len(), 0);
2382         assert_eq!(nodes[3].node.list_channels().len(), 1);
2383
2384         { // Cheat and reset nodes[4]'s height to 1
2385                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2386                 connect_block(&nodes[4], &Block { header, txdata: vec![] }, 1);
2387         }
2388
2389         assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
2390         assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
2391         // One pending HTLC to time out:
2392         let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2393         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2394         // buffer space).
2395
2396         {
2397                 let mut block = Block {
2398                         header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2399                         txdata: vec![],
2400                 };
2401                 connect_block(&nodes[3], &block, 2);
2402                 for i in 3..TEST_FINAL_CLTV + 2 + LATENCY_GRACE_PERIOD_BLOCKS + 1 {
2403                         block = Block {
2404                                 header: BlockHeader { version: 0x20000000, prev_blockhash: block.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2405                                 txdata: vec![],
2406                         };
2407                         connect_block(&nodes[3], &block, i);
2408                 }
2409                 check_added_monitors!(nodes[3], 1);
2410
2411                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2412                 {
2413                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2414                         node_txn.retain(|tx| {
2415                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2416                                         false
2417                                 } else { true }
2418                         });
2419                 }
2420
2421                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2422
2423                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2424                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, 3_000_000);
2425
2426                 block = Block {
2427                         header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2428                         txdata: vec![],
2429                 };
2430
2431                 connect_block(&nodes[4], &block, 2);
2432                 for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
2433                         block = Block {
2434                                 header: BlockHeader { version: 0x20000000, prev_blockhash: block.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2435                                 txdata: vec![],
2436                         };
2437                         connect_block(&nodes[4], &block, i);
2438                 }
2439
2440                 check_added_monitors!(nodes[4], 1);
2441                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2442
2443                 block = Block {
2444                         header: BlockHeader { version: 0x20000000, prev_blockhash: block.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2445                         txdata: vec![node_txn[0].clone()],
2446                 };
2447                 connect_block(&nodes[4], &block, TEST_FINAL_CLTV - 5);
2448
2449                 check_preimage_claim(&nodes[4], &node_txn);
2450         }
2451         get_announce_close_broadcast_events(&nodes, 3, 4);
2452         assert_eq!(nodes[3].node.list_channels().len(), 0);
2453         assert_eq!(nodes[4].node.list_channels().len(), 0);
2454 }
2455
2456 #[test]
2457 fn test_justice_tx() {
2458         // Test justice txn built on revoked HTLC-Success tx, against both sides
2459         let mut alice_config = UserConfig::default();
2460         alice_config.channel_options.announced_channel = true;
2461         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2462         alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2463         let mut bob_config = UserConfig::default();
2464         bob_config.channel_options.announced_channel = true;
2465         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2466         bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2467         let user_cfgs = [Some(alice_config), Some(bob_config)];
2468         let chanmon_cfgs = create_chanmon_cfgs(2);
2469         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2470         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2471         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2472         // Create some new channels:
2473         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2474
2475         // A pending HTLC which will be revoked:
2476         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2477         // Get the will-be-revoked local txn from nodes[0]
2478         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2479         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2480         assert_eq!(revoked_local_txn[0].input.len(), 1);
2481         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2482         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2483         assert_eq!(revoked_local_txn[1].input.len(), 1);
2484         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2485         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2486         // Revoke the old state
2487         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 3_000_000);
2488
2489         {
2490                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2491                 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2492                 {
2493                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2494                         assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2495                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2496
2497                         check_spends!(node_txn[0], revoked_local_txn[0]);
2498                         node_txn.swap_remove(0);
2499                         node_txn.truncate(1);
2500                 }
2501                 check_added_monitors!(nodes[1], 1);
2502                 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2503
2504                 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2505                 // Verify broadcast of revoked HTLC-timeout
2506                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2507                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2508                 check_added_monitors!(nodes[0], 1);
2509                 // Broadcast revoked HTLC-timeout on node 1
2510                 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2511                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2512         }
2513         get_announce_close_broadcast_events(&nodes, 0, 1);
2514
2515         assert_eq!(nodes[0].node.list_channels().len(), 0);
2516         assert_eq!(nodes[1].node.list_channels().len(), 0);
2517
2518         // We test justice_tx build by A on B's revoked HTLC-Success tx
2519         // Create some new channels:
2520         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2521         {
2522                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2523                 node_txn.clear();
2524         }
2525
2526         // A pending HTLC which will be revoked:
2527         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2528         // Get the will-be-revoked local txn from B
2529         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2530         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2531         assert_eq!(revoked_local_txn[0].input.len(), 1);
2532         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2533         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2534         // Revoke the old state
2535         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4, 3_000_000);
2536         {
2537                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2538                 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2539                 {
2540                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2541                         assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2542                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2543
2544                         check_spends!(node_txn[0], revoked_local_txn[0]);
2545                         node_txn.swap_remove(0);
2546                 }
2547                 check_added_monitors!(nodes[0], 1);
2548                 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2549
2550                 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2551                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2552                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2553                 check_added_monitors!(nodes[1], 1);
2554                 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2555                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2556         }
2557         get_announce_close_broadcast_events(&nodes, 0, 1);
2558         assert_eq!(nodes[0].node.list_channels().len(), 0);
2559         assert_eq!(nodes[1].node.list_channels().len(), 0);
2560 }
2561
2562 #[test]
2563 fn revoked_output_claim() {
2564         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2565         // transaction is broadcast by its counterparty
2566         let chanmon_cfgs = create_chanmon_cfgs(2);
2567         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2568         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2569         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2570         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2571         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2572         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2573         assert_eq!(revoked_local_txn.len(), 1);
2574         // Only output is the full channel value back to nodes[0]:
2575         assert_eq!(revoked_local_txn[0].output.len(), 1);
2576         // Send a payment through, updating everyone's latest commitment txn
2577         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000, 5_000_000);
2578
2579         // Inform nodes[1] that nodes[0] broadcast a stale tx
2580         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2581         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2582         check_added_monitors!(nodes[1], 1);
2583         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2584         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2585
2586         check_spends!(node_txn[0], revoked_local_txn[0]);
2587         check_spends!(node_txn[1], chan_1.3);
2588
2589         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2590         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2591         get_announce_close_broadcast_events(&nodes, 0, 1);
2592         check_added_monitors!(nodes[0], 1)
2593 }
2594
2595 #[test]
2596 fn claim_htlc_outputs_shared_tx() {
2597         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2598         let chanmon_cfgs = create_chanmon_cfgs(2);
2599         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2600         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2601         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2602
2603         // Create some new channel:
2604         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2605
2606         // Rebalance the network to generate htlc in the two directions
2607         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2608         // 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
2609         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2610         let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2611
2612         // Get the will-be-revoked local txn from node[0]
2613         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2614         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2615         assert_eq!(revoked_local_txn[0].input.len(), 1);
2616         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2617         assert_eq!(revoked_local_txn[1].input.len(), 1);
2618         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2619         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2620         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2621
2622         //Revoke the old state
2623         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2624
2625         {
2626                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2627                 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2628                 check_added_monitors!(nodes[0], 1);
2629                 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2630                 check_added_monitors!(nodes[1], 1);
2631                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2632                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2633
2634                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2635                 assert_eq!(node_txn.len(), 3); // ChannelMonitor: penalty tx, ChannelManager: local commitment + HTLC-timeout
2636
2637                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2638                 check_spends!(node_txn[0], revoked_local_txn[0]);
2639
2640                 let mut witness_lens = BTreeSet::new();
2641                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2642                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2643                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2644                 assert_eq!(witness_lens.len(), 3);
2645                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2646                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2647                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2648
2649                 // Next nodes[1] broadcasts its current local tx state:
2650                 assert_eq!(node_txn[1].input.len(), 1);
2651                 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2652
2653                 assert_eq!(node_txn[2].input.len(), 1);
2654                 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
2655                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2656                 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
2657                 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
2658                 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
2659         }
2660         get_announce_close_broadcast_events(&nodes, 0, 1);
2661         assert_eq!(nodes[0].node.list_channels().len(), 0);
2662         assert_eq!(nodes[1].node.list_channels().len(), 0);
2663 }
2664
2665 #[test]
2666 fn claim_htlc_outputs_single_tx() {
2667         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2668         let chanmon_cfgs = create_chanmon_cfgs(2);
2669         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2670         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2671         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2672
2673         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2674
2675         // Rebalance the network to generate htlc in the two directions
2676         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2677         // 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
2678         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2679         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2680         let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2681
2682         // Get the will-be-revoked local txn from node[0]
2683         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2684
2685         //Revoke the old state
2686         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2687
2688         {
2689                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2690                 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2691                 check_added_monitors!(nodes[0], 1);
2692                 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2693                 check_added_monitors!(nodes[1], 1);
2694                 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
2695
2696                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 200, true, header.bitcoin_hash());
2697                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2698
2699                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2700                 assert_eq!(node_txn.len(), 9);
2701                 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2702                 // ChannelManager: local commmitment + local HTLC-timeout (2)
2703                 // 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)
2704                 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2705
2706                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2707                 assert_eq!(node_txn[2].input.len(), 1);
2708                 check_spends!(node_txn[2], chan_1.3);
2709                 assert_eq!(node_txn[3].input.len(), 1);
2710                 let witness_script = node_txn[3].input[0].witness.last().unwrap();
2711                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2712                 check_spends!(node_txn[3], node_txn[2]);
2713
2714                 // Justice transactions are indices 1-2-4
2715                 assert_eq!(node_txn[0].input.len(), 1);
2716                 assert_eq!(node_txn[1].input.len(), 1);
2717                 assert_eq!(node_txn[4].input.len(), 1);
2718
2719                 check_spends!(node_txn[0], revoked_local_txn[0]);
2720                 check_spends!(node_txn[1], revoked_local_txn[0]);
2721                 check_spends!(node_txn[4], revoked_local_txn[0]);
2722
2723                 let mut witness_lens = BTreeSet::new();
2724                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2725                 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2726                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2727                 assert_eq!(witness_lens.len(), 3);
2728                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2729                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2730                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2731         }
2732         get_announce_close_broadcast_events(&nodes, 0, 1);
2733         assert_eq!(nodes[0].node.list_channels().len(), 0);
2734         assert_eq!(nodes[1].node.list_channels().len(), 0);
2735 }
2736
2737 #[test]
2738 fn test_htlc_on_chain_success() {
2739         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2740         // the preimage backward accordingly. So here we test that ChannelManager is
2741         // broadcasting the right event to other nodes in payment path.
2742         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2743         // A --------------------> B ----------------------> C (preimage)
2744         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2745         // commitment transaction was broadcast.
2746         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2747         // towards B.
2748         // B should be able to claim via preimage if A then broadcasts its local tx.
2749         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2750         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2751         // PaymentSent event).
2752
2753         let chanmon_cfgs = create_chanmon_cfgs(3);
2754         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2755         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2756         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2757
2758         // Create some initial channels
2759         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2760         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2761
2762         // Rebalance the network a bit by relaying one payment through all the channels...
2763         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2764         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2765
2766         let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2767         let (our_payment_preimage_2, _payment_hash_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2768         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2769
2770         // Broadcast legit commitment tx from C on B's chain
2771         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2772         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2773         assert_eq!(commitment_tx.len(), 1);
2774         check_spends!(commitment_tx[0], chan_2.3);
2775         nodes[2].node.claim_funds(our_payment_preimage, &None, 3_000_000);
2776         nodes[2].node.claim_funds(our_payment_preimage_2, &None, 3_000_000);
2777         check_added_monitors!(nodes[2], 2);
2778         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2779         assert!(updates.update_add_htlcs.is_empty());
2780         assert!(updates.update_fail_htlcs.is_empty());
2781         assert!(updates.update_fail_malformed_htlcs.is_empty());
2782         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2783
2784         connect_block(&nodes[2], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2785         check_closed_broadcast!(nodes[2], false);
2786         check_added_monitors!(nodes[2], 1);
2787         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)
2788         assert_eq!(node_txn.len(), 5);
2789         assert_eq!(node_txn[0], node_txn[3]);
2790         assert_eq!(node_txn[1], node_txn[4]);
2791         assert_eq!(node_txn[2], commitment_tx[0]);
2792         check_spends!(node_txn[0], commitment_tx[0]);
2793         check_spends!(node_txn[1], commitment_tx[0]);
2794         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2795         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2796         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2797         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2798         assert_eq!(node_txn[0].lock_time, 0);
2799         assert_eq!(node_txn[1].lock_time, 0);
2800
2801         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2802         connect_block(&nodes[1], &Block { header, txdata: node_txn}, 1);
2803         {
2804                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2805                 assert_eq!(added_monitors.len(), 1);
2806                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2807                 added_monitors.clear();
2808         }
2809         let events = nodes[1].node.get_and_clear_pending_msg_events();
2810         {
2811                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2812                 assert_eq!(added_monitors.len(), 2);
2813                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2814                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2815                 added_monitors.clear();
2816         }
2817         assert_eq!(events.len(), 2);
2818         match events[0] {
2819                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2820                 _ => panic!("Unexpected event"),
2821         }
2822         match events[1] {
2823                 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, .. } } => {
2824                         assert!(update_add_htlcs.is_empty());
2825                         assert!(update_fail_htlcs.is_empty());
2826                         assert_eq!(update_fulfill_htlcs.len(), 1);
2827                         assert!(update_fail_malformed_htlcs.is_empty());
2828                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2829                 },
2830                 _ => panic!("Unexpected event"),
2831         };
2832         macro_rules! check_tx_local_broadcast {
2833                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2834                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2835                         assert_eq!(node_txn.len(), 5);
2836                         // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2837                         // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2838                         check_spends!(node_txn[0], $commitment_tx);
2839                         check_spends!(node_txn[1], $commitment_tx);
2840                         assert_ne!(node_txn[0].lock_time, 0);
2841                         assert_ne!(node_txn[1].lock_time, 0);
2842                         if $htlc_offered {
2843                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2844                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2845                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2846                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2847                         } else {
2848                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2849                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2850                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2851                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2852                         }
2853                         check_spends!(node_txn[2], $chan_tx);
2854                         check_spends!(node_txn[3], node_txn[2]);
2855                         check_spends!(node_txn[4], node_txn[2]);
2856                         assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), 71);
2857                         assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2858                         assert_eq!(node_txn[4].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2859                         assert!(node_txn[3].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2860                         assert!(node_txn[4].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2861                         assert_ne!(node_txn[3].lock_time, 0);
2862                         assert_ne!(node_txn[4].lock_time, 0);
2863                         node_txn.clear();
2864                 } }
2865         }
2866         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2867         // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2868         // timeout-claim of the output that nodes[2] just claimed via success.
2869         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2870
2871         // Broadcast legit commitment tx from A on B's chain
2872         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2873         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2874         check_spends!(commitment_tx[0], chan_1.3);
2875         connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2876         check_closed_broadcast!(nodes[1], false);
2877         check_added_monitors!(nodes[1], 1);
2878         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 1 (HTLC-Success)
2879         assert_eq!(node_txn.len(), 4);
2880         check_spends!(node_txn[0], commitment_tx[0]);
2881         assert_eq!(node_txn[0].input.len(), 2);
2882         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2883         assert_eq!(node_txn[0].input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2884         assert_eq!(node_txn[0].lock_time, 0);
2885         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2886         check_spends!(node_txn[1], chan_1.3);
2887         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
2888         check_spends!(node_txn[2], node_txn[1]);
2889         check_spends!(node_txn[3], node_txn[1]);
2890         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2891         // we already checked the same situation with A.
2892
2893         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2894         connect_block(&nodes[0], &Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
2895         check_closed_broadcast!(nodes[0], false);
2896         check_added_monitors!(nodes[0], 1);
2897         let events = nodes[0].node.get_and_clear_pending_events();
2898         assert_eq!(events.len(), 2);
2899         let mut first_claimed = false;
2900         for event in events {
2901                 match event {
2902                         Event::PaymentSent { payment_preimage } => {
2903                                 if payment_preimage == our_payment_preimage {
2904                                         assert!(!first_claimed);
2905                                         first_claimed = true;
2906                                 } else {
2907                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2908                                 }
2909                         },
2910                         _ => panic!("Unexpected event"),
2911                 }
2912         }
2913         check_tx_local_broadcast!(nodes[0], true, commitment_tx[0], chan_1.3);
2914 }
2915
2916 #[test]
2917 fn test_htlc_on_chain_timeout() {
2918         // Test that in case of a unilateral close onchain, we detect the state of output and
2919         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2920         // broadcasting the right event to other nodes in payment path.
2921         // A ------------------> B ----------------------> C (timeout)
2922         //    B's commitment tx                 C's commitment tx
2923         //            \                                  \
2924         //         B's HTLC timeout tx               B's timeout tx
2925
2926         let chanmon_cfgs = create_chanmon_cfgs(3);
2927         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2928         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2929         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2930
2931         // Create some intial channels
2932         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2933         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2934
2935         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2936         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2937         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2938
2939         let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2940         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2941
2942         // Broadcast legit commitment tx from C on B's chain
2943         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2944         check_spends!(commitment_tx[0], chan_2.3);
2945         nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
2946         check_added_monitors!(nodes[2], 0);
2947         expect_pending_htlcs_forwardable!(nodes[2]);
2948         check_added_monitors!(nodes[2], 1);
2949
2950         let events = nodes[2].node.get_and_clear_pending_msg_events();
2951         assert_eq!(events.len(), 1);
2952         match events[0] {
2953                 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, .. } } => {
2954                         assert!(update_add_htlcs.is_empty());
2955                         assert!(!update_fail_htlcs.is_empty());
2956                         assert!(update_fulfill_htlcs.is_empty());
2957                         assert!(update_fail_malformed_htlcs.is_empty());
2958                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2959                 },
2960                 _ => panic!("Unexpected event"),
2961         };
2962         connect_block(&nodes[2], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2963         check_closed_broadcast!(nodes[2], false);
2964         check_added_monitors!(nodes[2], 1);
2965         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2966         assert_eq!(node_txn.len(), 1);
2967         check_spends!(node_txn[0], chan_2.3);
2968         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2969
2970         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2971         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2972         connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
2973         let timeout_tx;
2974         {
2975                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2976                 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2977                 assert_eq!(node_txn[1], node_txn[3]);
2978                 assert_eq!(node_txn[2], node_txn[4]);
2979
2980                 check_spends!(node_txn[0], commitment_tx[0]);
2981                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2982
2983                 check_spends!(node_txn[1], chan_2.3);
2984                 check_spends!(node_txn[2], node_txn[1]);
2985                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
2986                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2987
2988                 timeout_tx = node_txn[0].clone();
2989                 node_txn.clear();
2990         }
2991
2992         connect_block(&nodes[1], &Block { header, txdata: vec![timeout_tx]}, 1);
2993         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2994         check_added_monitors!(nodes[1], 1);
2995         check_closed_broadcast!(nodes[1], false);
2996
2997         expect_pending_htlcs_forwardable!(nodes[1]);
2998         check_added_monitors!(nodes[1], 1);
2999         let events = nodes[1].node.get_and_clear_pending_msg_events();
3000         assert_eq!(events.len(), 1);
3001         match events[0] {
3002                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
3003                         assert!(update_add_htlcs.is_empty());
3004                         assert!(!update_fail_htlcs.is_empty());
3005                         assert!(update_fulfill_htlcs.is_empty());
3006                         assert!(update_fail_malformed_htlcs.is_empty());
3007                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3008                 },
3009                 _ => panic!("Unexpected event"),
3010         };
3011         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
3012         assert_eq!(node_txn.len(), 0);
3013
3014         // Broadcast legit commitment tx from B on A's chain
3015         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3016         check_spends!(commitment_tx[0], chan_1.3);
3017
3018         connect_block(&nodes[0], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
3019         check_closed_broadcast!(nodes[0], false);
3020         check_added_monitors!(nodes[0], 1);
3021         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 1 timeout tx
3022         assert_eq!(node_txn.len(), 3);
3023         check_spends!(node_txn[0], commitment_tx[0]);
3024         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3025         check_spends!(node_txn[1], chan_1.3);
3026         check_spends!(node_txn[2], node_txn[1]);
3027         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
3028         assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3029 }
3030
3031 #[test]
3032 fn test_simple_commitment_revoked_fail_backward() {
3033         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3034         // and fail backward accordingly.
3035
3036         let chanmon_cfgs = create_chanmon_cfgs(3);
3037         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3038         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3039         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3040
3041         // Create some initial channels
3042         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3043         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3044
3045         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3046         // Get the will-be-revoked local txn from nodes[2]
3047         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3048         // Revoke the old state
3049         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, 3_000_000);
3050
3051         let (_, payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3052
3053         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
3054         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3055         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
3056         check_added_monitors!(nodes[1], 1);
3057         check_closed_broadcast!(nodes[1], false);
3058
3059         expect_pending_htlcs_forwardable!(nodes[1]);
3060         check_added_monitors!(nodes[1], 1);
3061         let events = nodes[1].node.get_and_clear_pending_msg_events();
3062         assert_eq!(events.len(), 1);
3063         match events[0] {
3064                 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, .. } } => {
3065                         assert!(update_add_htlcs.is_empty());
3066                         assert_eq!(update_fail_htlcs.len(), 1);
3067                         assert!(update_fulfill_htlcs.is_empty());
3068                         assert!(update_fail_malformed_htlcs.is_empty());
3069                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3070
3071                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3072                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3073
3074                         let events = nodes[0].node.get_and_clear_pending_msg_events();
3075                         assert_eq!(events.len(), 1);
3076                         match events[0] {
3077                                 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3078                                 _ => panic!("Unexpected event"),
3079                         }
3080                         expect_payment_failed!(nodes[0], payment_hash, false);
3081                 },
3082                 _ => panic!("Unexpected event"),
3083         }
3084 }
3085
3086 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3087         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3088         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3089         // commitment transaction anymore.
3090         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3091         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3092         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3093         // technically disallowed and we should probably handle it reasonably.
3094         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3095         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3096         // transactions:
3097         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3098         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3099         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3100         //   and once they revoke the previous commitment transaction (allowing us to send a new
3101         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3102         let chanmon_cfgs = create_chanmon_cfgs(3);
3103         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3104         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3105         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3106
3107         // Create some initial channels
3108         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3109         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3110
3111         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3112         // Get the will-be-revoked local txn from nodes[2]
3113         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3114         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3115         // Revoke the old state
3116         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, if no_to_remote { 10_000 } else { 3_000_000});
3117
3118         let value = if use_dust {
3119                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3120                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3121                 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().our_dust_limit_satoshis * 1000
3122         } else { 3000000 };
3123
3124         let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3125         let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3126         let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3127
3128         assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, &None));
3129         expect_pending_htlcs_forwardable!(nodes[2]);
3130         check_added_monitors!(nodes[2], 1);
3131         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3132         assert!(updates.update_add_htlcs.is_empty());
3133         assert!(updates.update_fulfill_htlcs.is_empty());
3134         assert!(updates.update_fail_malformed_htlcs.is_empty());
3135         assert_eq!(updates.update_fail_htlcs.len(), 1);
3136         assert!(updates.update_fee.is_none());
3137         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3138         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3139         // Drop the last RAA from 3 -> 2
3140
3141         assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, &None));
3142         expect_pending_htlcs_forwardable!(nodes[2]);
3143         check_added_monitors!(nodes[2], 1);
3144         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3145         assert!(updates.update_add_htlcs.is_empty());
3146         assert!(updates.update_fulfill_htlcs.is_empty());
3147         assert!(updates.update_fail_malformed_htlcs.is_empty());
3148         assert_eq!(updates.update_fail_htlcs.len(), 1);
3149         assert!(updates.update_fee.is_none());
3150         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3151         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3152         check_added_monitors!(nodes[1], 1);
3153         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3154         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3155         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3156         check_added_monitors!(nodes[2], 1);
3157
3158         assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, &None));
3159         expect_pending_htlcs_forwardable!(nodes[2]);
3160         check_added_monitors!(nodes[2], 1);
3161         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3162         assert!(updates.update_add_htlcs.is_empty());
3163         assert!(updates.update_fulfill_htlcs.is_empty());
3164         assert!(updates.update_fail_malformed_htlcs.is_empty());
3165         assert_eq!(updates.update_fail_htlcs.len(), 1);
3166         assert!(updates.update_fee.is_none());
3167         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3168         // At this point first_payment_hash has dropped out of the latest two commitment
3169         // transactions that nodes[1] is tracking...
3170         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3171         check_added_monitors!(nodes[1], 1);
3172         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3173         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3174         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3175         check_added_monitors!(nodes[2], 1);
3176
3177         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3178         // on nodes[2]'s RAA.
3179         let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3180         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3181         let logger = test_utils::TestLogger::new();
3182         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();
3183         nodes[1].node.send_payment(&route, fourth_payment_hash, &None).unwrap();
3184         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3185         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3186         check_added_monitors!(nodes[1], 0);
3187
3188         if deliver_bs_raa {
3189                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3190                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3191                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3192                 check_added_monitors!(nodes[1], 1);
3193                 let events = nodes[1].node.get_and_clear_pending_events();
3194                 assert_eq!(events.len(), 1);
3195                 match events[0] {
3196                         Event::PendingHTLCsForwardable { .. } => { },
3197                         _ => panic!("Unexpected event"),
3198                 };
3199                 // Deliberately don't process the pending fail-back so they all fail back at once after
3200                 // block connection just like the !deliver_bs_raa case
3201         }
3202
3203         let mut failed_htlcs = HashSet::new();
3204         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3205
3206         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
3207         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3208         check_added_monitors!(nodes[1], 1);
3209         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
3210
3211         let events = nodes[1].node.get_and_clear_pending_events();
3212         assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
3213         match events[0] {
3214                 Event::PaymentFailed { ref payment_hash, .. } => {
3215                         assert_eq!(*payment_hash, fourth_payment_hash);
3216                 },
3217                 _ => panic!("Unexpected event"),
3218         }
3219         if !deliver_bs_raa {
3220                 match events[1] {
3221                         Event::PendingHTLCsForwardable { .. } => { },
3222                         _ => panic!("Unexpected event"),
3223                 };
3224         }
3225         nodes[1].node.process_pending_htlc_forwards();
3226         check_added_monitors!(nodes[1], 1);
3227
3228         let events = nodes[1].node.get_and_clear_pending_msg_events();
3229         assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
3230         match events[if deliver_bs_raa { 1 } else { 0 }] {
3231                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3232                 _ => panic!("Unexpected event"),
3233         }
3234         if deliver_bs_raa {
3235                 match events[0] {
3236                         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, .. } } => {
3237                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3238                                 assert_eq!(update_add_htlcs.len(), 1);
3239                                 assert!(update_fulfill_htlcs.is_empty());
3240                                 assert!(update_fail_htlcs.is_empty());
3241                                 assert!(update_fail_malformed_htlcs.is_empty());
3242                         },
3243                         _ => panic!("Unexpected event"),
3244                 }
3245         }
3246         match events[if deliver_bs_raa { 2 } else { 1 }] {
3247                 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, .. } } => {
3248                         assert!(update_add_htlcs.is_empty());
3249                         assert_eq!(update_fail_htlcs.len(), 3);
3250                         assert!(update_fulfill_htlcs.is_empty());
3251                         assert!(update_fail_malformed_htlcs.is_empty());
3252                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3253
3254                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3255                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3256                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3257
3258                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3259
3260                         let events = nodes[0].node.get_and_clear_pending_msg_events();
3261                         // If we delivered B's RAA we got an unknown preimage error, not something
3262                         // that we should update our routing table for.
3263                         assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
3264                         for event in events {
3265                                 match event {
3266                                         MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3267                                         _ => panic!("Unexpected event"),
3268                                 }
3269                         }
3270                         let events = nodes[0].node.get_and_clear_pending_events();
3271                         assert_eq!(events.len(), 3);
3272                         match events[0] {
3273                                 Event::PaymentFailed { ref payment_hash, .. } => {
3274                                         assert!(failed_htlcs.insert(payment_hash.0));
3275                                 },
3276                                 _ => panic!("Unexpected event"),
3277                         }
3278                         match events[1] {
3279                                 Event::PaymentFailed { ref payment_hash, .. } => {
3280                                         assert!(failed_htlcs.insert(payment_hash.0));
3281                                 },
3282                                 _ => panic!("Unexpected event"),
3283                         }
3284                         match events[2] {
3285                                 Event::PaymentFailed { ref payment_hash, .. } => {
3286                                         assert!(failed_htlcs.insert(payment_hash.0));
3287                                 },
3288                                 _ => panic!("Unexpected event"),
3289                         }
3290                 },
3291                 _ => panic!("Unexpected event"),
3292         }
3293
3294         assert!(failed_htlcs.contains(&first_payment_hash.0));
3295         assert!(failed_htlcs.contains(&second_payment_hash.0));
3296         assert!(failed_htlcs.contains(&third_payment_hash.0));
3297 }
3298
3299 #[test]
3300 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3301         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3302         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3303         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3304         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3305 }
3306
3307 #[test]
3308 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3309         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3310         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3311         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3312         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3313 }
3314
3315 #[test]
3316 fn fail_backward_pending_htlc_upon_channel_failure() {
3317         let chanmon_cfgs = create_chanmon_cfgs(2);
3318         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3319         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3320         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3321         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3322         let logger = test_utils::TestLogger::new();
3323
3324         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3325         {
3326                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
3327                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3328                 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();
3329                 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
3330                 check_added_monitors!(nodes[0], 1);
3331
3332                 let payment_event = {
3333                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3334                         assert_eq!(events.len(), 1);
3335                         SendEvent::from_event(events.remove(0))
3336                 };
3337                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3338                 assert_eq!(payment_event.msgs.len(), 1);
3339         }
3340
3341         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3342         let (_, failed_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3343         {
3344                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3345                 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();
3346                 nodes[0].node.send_payment(&route, failed_payment_hash, &None).unwrap();
3347                 check_added_monitors!(nodes[0], 0);
3348
3349                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3350         }
3351
3352         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3353         {
3354                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[1]);
3355
3356                 let secp_ctx = Secp256k1::new();
3357                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3358                 let current_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
3359                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3360                 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();
3361                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &None, current_height).unwrap();
3362                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3363                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3364
3365                 // Send a 0-msat update_add_htlc to fail the channel.
3366                 let update_add_htlc = msgs::UpdateAddHTLC {
3367                         channel_id: chan.2,
3368                         htlc_id: 0,
3369                         amount_msat: 0,
3370                         payment_hash,
3371                         cltv_expiry,
3372                         onion_routing_packet,
3373                 };
3374                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3375         }
3376
3377         // Check that Alice fails backward the pending HTLC from the second payment.
3378         expect_payment_failed!(nodes[0], failed_payment_hash, true);
3379         check_closed_broadcast!(nodes[0], true);
3380         check_added_monitors!(nodes[0], 1);
3381 }
3382
3383 #[test]
3384 fn test_htlc_ignore_latest_remote_commitment() {
3385         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3386         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3387         let chanmon_cfgs = create_chanmon_cfgs(2);
3388         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3389         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3390         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3391         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3392
3393         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3394         nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
3395         check_closed_broadcast!(nodes[0], false);
3396         check_added_monitors!(nodes[0], 1);
3397
3398         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3399         assert_eq!(node_txn.len(), 2);
3400
3401         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3402         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3403         check_closed_broadcast!(nodes[1], false);
3404         check_added_monitors!(nodes[1], 1);
3405
3406         // Duplicate the block_connected call since this may happen due to other listeners
3407         // registering new transactions
3408         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3409 }
3410
3411 #[test]
3412 fn test_force_close_fail_back() {
3413         // Check which HTLCs are failed-backwards on channel force-closure
3414         let chanmon_cfgs = create_chanmon_cfgs(3);
3415         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3416         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3417         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3418         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3419         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3420         let logger = test_utils::TestLogger::new();
3421
3422         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3423
3424         let mut payment_event = {
3425                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3426                 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();
3427                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
3428                 check_added_monitors!(nodes[0], 1);
3429
3430                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3431                 assert_eq!(events.len(), 1);
3432                 SendEvent::from_event(events.remove(0))
3433         };
3434
3435         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3436         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3437
3438         expect_pending_htlcs_forwardable!(nodes[1]);
3439
3440         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3441         assert_eq!(events_2.len(), 1);
3442         payment_event = SendEvent::from_event(events_2.remove(0));
3443         assert_eq!(payment_event.msgs.len(), 1);
3444
3445         check_added_monitors!(nodes[1], 1);
3446         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3447         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3448         check_added_monitors!(nodes[2], 1);
3449         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3450
3451         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3452         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3453         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3454
3455         nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
3456         check_closed_broadcast!(nodes[2], false);
3457         check_added_monitors!(nodes[2], 1);
3458         let tx = {
3459                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3460                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3461                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3462                 // back to nodes[1] upon timeout otherwise.
3463                 assert_eq!(node_txn.len(), 1);
3464                 node_txn.remove(0)
3465         };
3466
3467         let block = Block {
3468                 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
3469                 txdata: vec![tx.clone()],
3470         };
3471         connect_block(&nodes[1], &block, 1);
3472
3473         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3474         check_closed_broadcast!(nodes[1], false);
3475         check_added_monitors!(nodes[1], 1);
3476
3477         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3478         {
3479                 let mut monitors = nodes[2].chain_monitor.chain_monitor.monitors.lock().unwrap();
3480                 monitors.get_mut(&OutPoint{ txid: Txid::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), index: 0 }).unwrap()
3481                         .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
3482         }
3483         connect_block(&nodes[2], &block, 1);
3484         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3485         assert_eq!(node_txn.len(), 1);
3486         assert_eq!(node_txn[0].input.len(), 1);
3487         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3488         assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3489         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3490
3491         check_spends!(node_txn[0], tx);
3492 }
3493
3494 #[test]
3495 fn test_unconf_chan() {
3496         // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
3497         let chanmon_cfgs = create_chanmon_cfgs(2);
3498         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3499         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3500         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3501         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3502
3503         let channel_state = nodes[0].node.channel_state.lock().unwrap();
3504         assert_eq!(channel_state.by_id.len(), 1);
3505         assert_eq!(channel_state.short_to_id.len(), 1);
3506         mem::drop(channel_state);
3507
3508         let mut headers = Vec::new();
3509         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3510         headers.push(header.clone());
3511         for _i in 2..100 {
3512                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3513                 headers.push(header.clone());
3514         }
3515         let mut height = 99;
3516         while !headers.is_empty() {
3517                 nodes[0].node.block_disconnected(&headers.pop().unwrap(), height);
3518                 height -= 1;
3519         }
3520         check_closed_broadcast!(nodes[0], false);
3521         check_added_monitors!(nodes[0], 1);
3522         let channel_state = nodes[0].node.channel_state.lock().unwrap();
3523         assert_eq!(channel_state.by_id.len(), 0);
3524         assert_eq!(channel_state.short_to_id.len(), 0);
3525 }
3526
3527 #[test]
3528 fn test_simple_peer_disconnect() {
3529         // Test that we can reconnect when there are no lost messages
3530         let chanmon_cfgs = create_chanmon_cfgs(3);
3531         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3532         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3533         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3534         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3535         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3536
3537         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3538         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3539         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3540
3541         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3542         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3543         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3544         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1, 1_000_000);
3545
3546         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3547         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3548         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3549
3550         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3551         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3552         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3553         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3554
3555         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3556         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3557
3558         claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3, 1_000_000);
3559         fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
3560
3561         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3562         {
3563                 let events = nodes[0].node.get_and_clear_pending_events();
3564                 assert_eq!(events.len(), 2);
3565                 match events[0] {
3566                         Event::PaymentSent { payment_preimage } => {
3567                                 assert_eq!(payment_preimage, payment_preimage_3);
3568                         },
3569                         _ => panic!("Unexpected event"),
3570                 }
3571                 match events[1] {
3572                         Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
3573                                 assert_eq!(payment_hash, payment_hash_5);
3574                                 assert!(rejected_by_dest);
3575                         },
3576                         _ => panic!("Unexpected event"),
3577                 }
3578         }
3579
3580         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4, 1_000_000);
3581         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3582 }
3583
3584 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
3585         // Test that we can reconnect when in-flight HTLC updates get dropped
3586         let chanmon_cfgs = create_chanmon_cfgs(2);
3587         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3588         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3589         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3590         if messages_delivered == 0 {
3591                 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3592                 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3593         } else {
3594                 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3595         }
3596
3597         let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
3598
3599         let logger = test_utils::TestLogger::new();
3600         let payment_event = {
3601                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3602                 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(), Some(&nodes[0].node.list_usable_channels()), &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3603                 nodes[0].node.send_payment(&route, payment_hash_1, &None).unwrap();
3604                 check_added_monitors!(nodes[0], 1);
3605
3606                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3607                 assert_eq!(events.len(), 1);
3608                 SendEvent::from_event(events.remove(0))
3609         };
3610         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3611
3612         if messages_delivered < 2 {
3613                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3614         } else {
3615                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3616                 if messages_delivered >= 3 {
3617                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3618                         check_added_monitors!(nodes[1], 1);
3619                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3620
3621                         if messages_delivered >= 4 {
3622                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3623                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3624                                 check_added_monitors!(nodes[0], 1);
3625
3626                                 if messages_delivered >= 5 {
3627                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3628                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3629                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3630                                         check_added_monitors!(nodes[0], 1);
3631
3632                                         if messages_delivered >= 6 {
3633                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3634                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3635                                                 check_added_monitors!(nodes[1], 1);
3636                                         }
3637                                 }
3638                         }
3639                 }
3640         }
3641
3642         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3643         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3644         if messages_delivered < 3 {
3645                 // Even if the funding_locked messages get exchanged, as long as nothing further was
3646                 // received on either side, both sides will need to resend them.
3647                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
3648         } else if messages_delivered == 3 {
3649                 // nodes[0] still wants its RAA + commitment_signed
3650                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
3651         } else if messages_delivered == 4 {
3652                 // nodes[0] still wants its commitment_signed
3653                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3654         } else if messages_delivered == 5 {
3655                 // nodes[1] still wants its final RAA
3656                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3657         } else if messages_delivered == 6 {
3658                 // Everything was delivered...
3659                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3660         }
3661
3662         let events_1 = nodes[1].node.get_and_clear_pending_events();
3663         assert_eq!(events_1.len(), 1);
3664         match events_1[0] {
3665                 Event::PendingHTLCsForwardable { .. } => { },
3666                 _ => panic!("Unexpected event"),
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         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3672
3673         nodes[1].node.process_pending_htlc_forwards();
3674
3675         let events_2 = nodes[1].node.get_and_clear_pending_events();
3676         assert_eq!(events_2.len(), 1);
3677         match events_2[0] {
3678                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
3679                         assert_eq!(payment_hash_1, *payment_hash);
3680                         assert_eq!(*payment_secret, None);
3681                         assert_eq!(amt, 1000000);
3682                 },
3683                 _ => panic!("Unexpected event"),
3684         }
3685
3686         nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000);
3687         check_added_monitors!(nodes[1], 1);
3688
3689         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3690         assert_eq!(events_3.len(), 1);
3691         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3692                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3693                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3694                         assert!(updates.update_add_htlcs.is_empty());
3695                         assert!(updates.update_fail_htlcs.is_empty());
3696                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3697                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3698                         assert!(updates.update_fee.is_none());
3699                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3700                 },
3701                 _ => panic!("Unexpected event"),
3702         };
3703
3704         if messages_delivered >= 1 {
3705                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3706
3707                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3708                 assert_eq!(events_4.len(), 1);
3709                 match events_4[0] {
3710                         Event::PaymentSent { ref payment_preimage } => {
3711                                 assert_eq!(payment_preimage_1, *payment_preimage);
3712                         },
3713                         _ => panic!("Unexpected event"),
3714                 }
3715
3716                 if messages_delivered >= 2 {
3717                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3718                         check_added_monitors!(nodes[0], 1);
3719                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3720
3721                         if messages_delivered >= 3 {
3722                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3723                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3724                                 check_added_monitors!(nodes[1], 1);
3725
3726                                 if messages_delivered >= 4 {
3727                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3728                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3729                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3730                                         check_added_monitors!(nodes[1], 1);
3731
3732                                         if messages_delivered >= 5 {
3733                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3734                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3735                                                 check_added_monitors!(nodes[0], 1);
3736                                         }
3737                                 }
3738                         }
3739                 }
3740         }
3741
3742         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3743         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3744         if messages_delivered < 2 {
3745                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
3746                 //TODO: Deduplicate PaymentSent events, then enable this if:
3747                 //if messages_delivered < 1 {
3748                         let events_4 = nodes[0].node.get_and_clear_pending_events();
3749                         assert_eq!(events_4.len(), 1);
3750                         match events_4[0] {
3751                                 Event::PaymentSent { ref payment_preimage } => {
3752                                         assert_eq!(payment_preimage_1, *payment_preimage);
3753                                 },
3754                                 _ => panic!("Unexpected event"),
3755                         }
3756                 //}
3757         } else if messages_delivered == 2 {
3758                 // nodes[0] still wants its RAA + commitment_signed
3759                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
3760         } else if messages_delivered == 3 {
3761                 // nodes[0] still wants its commitment_signed
3762                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
3763         } else if messages_delivered == 4 {
3764                 // nodes[1] still wants its final RAA
3765                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3766         } else if messages_delivered == 5 {
3767                 // Everything was delivered...
3768                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3769         }
3770
3771         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3772         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3773         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3774
3775         // Channel should still work fine...
3776         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3777         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(), Some(&nodes[0].node.list_usable_channels()), &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3778         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3779         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3780 }
3781
3782 #[test]
3783 fn test_drop_messages_peer_disconnect_a() {
3784         do_test_drop_messages_peer_disconnect(0);
3785         do_test_drop_messages_peer_disconnect(1);
3786         do_test_drop_messages_peer_disconnect(2);
3787         do_test_drop_messages_peer_disconnect(3);
3788 }
3789
3790 #[test]
3791 fn test_drop_messages_peer_disconnect_b() {
3792         do_test_drop_messages_peer_disconnect(4);
3793         do_test_drop_messages_peer_disconnect(5);
3794         do_test_drop_messages_peer_disconnect(6);
3795 }
3796
3797 #[test]
3798 fn test_funding_peer_disconnect() {
3799         // Test that we can lock in our funding tx while disconnected
3800         let chanmon_cfgs = create_chanmon_cfgs(2);
3801         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3802         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3803         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3804         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3805
3806         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3807         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3808
3809         confirm_transaction(&nodes[0], &tx);
3810         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3811         assert_eq!(events_1.len(), 1);
3812         match events_1[0] {
3813                 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3814                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3815                 },
3816                 _ => panic!("Unexpected event"),
3817         }
3818
3819         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3820
3821         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3822         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3823
3824         confirm_transaction(&nodes[1], &tx);
3825         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3826         assert_eq!(events_2.len(), 2);
3827         let funding_locked = match events_2[0] {
3828                 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3829                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3830                         msg.clone()
3831                 },
3832                 _ => panic!("Unexpected event"),
3833         };
3834         let bs_announcement_sigs = match events_2[1] {
3835                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3836                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3837                         msg.clone()
3838                 },
3839                 _ => panic!("Unexpected event"),
3840         };
3841
3842         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3843
3844         nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3845         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3846         let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3847         assert_eq!(events_3.len(), 2);
3848         let as_announcement_sigs = match events_3[0] {
3849                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3850                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3851                         msg.clone()
3852                 },
3853                 _ => panic!("Unexpected event"),
3854         };
3855         let (as_announcement, as_update) = match events_3[1] {
3856                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3857                         (msg.clone(), update_msg.clone())
3858                 },
3859                 _ => panic!("Unexpected event"),
3860         };
3861
3862         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3863         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3864         assert_eq!(events_4.len(), 1);
3865         let (_, bs_update) = match events_4[0] {
3866                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3867                         (msg.clone(), update_msg.clone())
3868                 },
3869                 _ => panic!("Unexpected event"),
3870         };
3871
3872         nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3873         nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3874         nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3875
3876         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3877         let logger = test_utils::TestLogger::new();
3878         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();
3879         let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3880         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage, 1_000_000);
3881 }
3882
3883 #[test]
3884 fn test_drop_messages_peer_disconnect_dual_htlc() {
3885         // Test that we can handle reconnecting when both sides of a channel have pending
3886         // commitment_updates when we disconnect.
3887         let chanmon_cfgs = create_chanmon_cfgs(2);
3888         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3889         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3890         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3891         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3892         let logger = test_utils::TestLogger::new();
3893
3894         let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3895
3896         // Now try to send a second payment which will fail to send
3897         let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
3898         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3899         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();
3900         nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
3901         check_added_monitors!(nodes[0], 1);
3902
3903         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3904         assert_eq!(events_1.len(), 1);
3905         match events_1[0] {
3906                 MessageSendEvent::UpdateHTLCs { .. } => {},
3907                 _ => panic!("Unexpected event"),
3908         }
3909
3910         assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000));
3911         check_added_monitors!(nodes[1], 1);
3912
3913         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3914         assert_eq!(events_2.len(), 1);
3915         match events_2[0] {
3916                 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 } } => {
3917                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3918                         assert!(update_add_htlcs.is_empty());
3919                         assert_eq!(update_fulfill_htlcs.len(), 1);
3920                         assert!(update_fail_htlcs.is_empty());
3921                         assert!(update_fail_malformed_htlcs.is_empty());
3922                         assert!(update_fee.is_none());
3923
3924                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3925                         let events_3 = nodes[0].node.get_and_clear_pending_events();
3926                         assert_eq!(events_3.len(), 1);
3927                         match events_3[0] {
3928                                 Event::PaymentSent { ref payment_preimage } => {
3929                                         assert_eq!(*payment_preimage, payment_preimage_1);
3930                                 },
3931                                 _ => panic!("Unexpected event"),
3932                         }
3933
3934                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3935                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3936                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3937                         check_added_monitors!(nodes[0], 1);
3938                 },
3939                 _ => panic!("Unexpected event"),
3940         }
3941
3942         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3943         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3944
3945         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3946         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3947         assert_eq!(reestablish_1.len(), 1);
3948         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3949         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3950         assert_eq!(reestablish_2.len(), 1);
3951
3952         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3953         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3954         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3955         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3956
3957         assert!(as_resp.0.is_none());
3958         assert!(bs_resp.0.is_none());
3959
3960         assert!(bs_resp.1.is_none());
3961         assert!(bs_resp.2.is_none());
3962
3963         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3964
3965         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3966         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3967         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3968         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3969         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3970         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
3971         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
3972         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3973         // No commitment_signed so get_event_msg's assert(len == 1) passes
3974         check_added_monitors!(nodes[1], 1);
3975
3976         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
3977         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3978         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3979         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3980         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3981         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3982         assert!(bs_second_commitment_signed.update_fee.is_none());
3983         check_added_monitors!(nodes[1], 1);
3984
3985         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3986         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3987         assert!(as_commitment_signed.update_add_htlcs.is_empty());
3988         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
3989         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
3990         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
3991         assert!(as_commitment_signed.update_fee.is_none());
3992         check_added_monitors!(nodes[0], 1);
3993
3994         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
3995         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3996         // No commitment_signed so get_event_msg's assert(len == 1) passes
3997         check_added_monitors!(nodes[0], 1);
3998
3999         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4000         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4001         // No commitment_signed so get_event_msg's assert(len == 1) passes
4002         check_added_monitors!(nodes[1], 1);
4003
4004         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4005         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4006         check_added_monitors!(nodes[1], 1);
4007
4008         expect_pending_htlcs_forwardable!(nodes[1]);
4009
4010         let events_5 = nodes[1].node.get_and_clear_pending_events();
4011         assert_eq!(events_5.len(), 1);
4012         match events_5[0] {
4013                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt: _ } => {
4014                         assert_eq!(payment_hash_2, *payment_hash);
4015                         assert_eq!(*payment_secret, None);
4016                 },
4017                 _ => panic!("Unexpected event"),
4018         }
4019
4020         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4021         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4022         check_added_monitors!(nodes[0], 1);
4023
4024         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
4025 }
4026
4027 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4028         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4029         // to avoid our counterparty failing the channel.
4030         let chanmon_cfgs = create_chanmon_cfgs(2);
4031         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4032         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4033         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4034
4035         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4036         let logger = test_utils::TestLogger::new();
4037
4038         let our_payment_hash = if send_partial_mpp {
4039                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4040                 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();
4041                 let (_, our_payment_hash) = get_payment_preimage_hash!(&nodes[0]);
4042                 let payment_secret = PaymentSecret([0xdb; 32]);
4043                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4044                 // indicates there are more HTLCs coming.
4045                 nodes[0].node.send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200000, CHAN_CONFIRM_DEPTH).unwrap();
4046                 check_added_monitors!(nodes[0], 1);
4047                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4048                 assert_eq!(events.len(), 1);
4049                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4050                 // hop should *not* yet generate any PaymentReceived event(s).
4051                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false);
4052                 our_payment_hash
4053         } else {
4054                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4055         };
4056
4057         let mut block = Block {
4058                 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4059                 txdata: vec![],
4060         };
4061         connect_block(&nodes[0], &block, 101);
4062         connect_block(&nodes[1], &block, 101);
4063         for i in 102..TEST_FINAL_CLTV + 100 + 1 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
4064                 block.header.prev_blockhash = block.bitcoin_hash();
4065                 connect_block(&nodes[0], &block, i);
4066                 connect_block(&nodes[1], &block, i);
4067         }
4068
4069         expect_pending_htlcs_forwardable!(nodes[1]);
4070
4071         check_added_monitors!(nodes[1], 1);
4072         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4073         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4074         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4075         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4076         assert!(htlc_timeout_updates.update_fee.is_none());
4077
4078         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4079         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4080         // 100_000 msat as u64, followed by a height of 123 as u32
4081         let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4082         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(123));
4083         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4084 }
4085
4086 #[test]
4087 fn test_htlc_timeout() {
4088         do_test_htlc_timeout(true);
4089         do_test_htlc_timeout(false);
4090 }
4091
4092 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4093         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4094         let chanmon_cfgs = create_chanmon_cfgs(3);
4095         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4096         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4097         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4098         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4099         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4100         let logger = test_utils::TestLogger::new();
4101
4102         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4103         let (_, first_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4104         {
4105                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4106                 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();
4107                 nodes[1].node.send_payment(&route, first_payment_hash, &None).unwrap();
4108         }
4109         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4110         check_added_monitors!(nodes[1], 1);
4111
4112         // Now attempt to route a second payment, which should be placed in the holding cell
4113         let (_, second_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4114         if forwarded_htlc {
4115                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4116                 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();
4117                 nodes[0].node.send_payment(&route, second_payment_hash, &None).unwrap();
4118                 check_added_monitors!(nodes[0], 1);
4119                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4120                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4121                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4122                 expect_pending_htlcs_forwardable!(nodes[1]);
4123                 check_added_monitors!(nodes[1], 0);
4124         } else {
4125                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4126                 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();
4127                 nodes[1].node.send_payment(&route, second_payment_hash, &None).unwrap();
4128                 check_added_monitors!(nodes[1], 0);
4129         }
4130
4131         let mut block = Block {
4132                 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4133                 txdata: vec![],
4134         };
4135         connect_block(&nodes[1], &block, 101);
4136         for i in 102..TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
4137                 block.header.prev_blockhash = block.bitcoin_hash();
4138                 connect_block(&nodes[1], &block, i);
4139         }
4140
4141         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4142         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4143
4144         block.header.prev_blockhash = block.bitcoin_hash();
4145         connect_block(&nodes[1], &block, TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS);
4146
4147         if forwarded_htlc {
4148                 expect_pending_htlcs_forwardable!(nodes[1]);
4149                 check_added_monitors!(nodes[1], 1);
4150                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4151                 assert_eq!(fail_commit.len(), 1);
4152                 match fail_commit[0] {
4153                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4154                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4155                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4156                         },
4157                         _ => unreachable!(),
4158                 }
4159                 expect_payment_failed!(nodes[0], second_payment_hash, false);
4160                 if let &MessageSendEvent::PaymentFailureNetworkUpdate { ref update } = &nodes[0].node.get_and_clear_pending_msg_events()[0] {
4161                         match update {
4162                                 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {},
4163                                 _ => panic!("Unexpected event"),
4164                         }
4165                 } else {
4166                         panic!("Unexpected event");
4167                 }
4168         } else {
4169                 expect_payment_failed!(nodes[1], second_payment_hash, true);
4170         }
4171 }
4172
4173 #[test]
4174 fn test_holding_cell_htlc_add_timeouts() {
4175         do_test_holding_cell_htlc_add_timeouts(false);
4176         do_test_holding_cell_htlc_add_timeouts(true);
4177 }
4178
4179 #[test]
4180 fn test_invalid_channel_announcement() {
4181         //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
4182         let secp_ctx = Secp256k1::new();
4183         let chanmon_cfgs = create_chanmon_cfgs(2);
4184         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4185         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4186         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4187
4188         let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
4189
4190         let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
4191         let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
4192         let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4193         let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4194
4195         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 } );
4196
4197         let as_bitcoin_key = as_chan.get_local_keys().inner.local_channel_pubkeys.funding_pubkey;
4198         let bs_bitcoin_key = bs_chan.get_local_keys().inner.local_channel_pubkeys.funding_pubkey;
4199
4200         let as_network_key = nodes[0].node.get_our_node_id();
4201         let bs_network_key = nodes[1].node.get_our_node_id();
4202
4203         let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
4204
4205         let mut chan_announcement;
4206
4207         macro_rules! dummy_unsigned_msg {
4208                 () => {
4209                         msgs::UnsignedChannelAnnouncement {
4210                                 features: ChannelFeatures::known(),
4211                                 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
4212                                 short_channel_id: as_chan.get_short_channel_id().unwrap(),
4213                                 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
4214                                 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
4215                                 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
4216                                 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
4217                                 excess_data: Vec::new(),
4218                         };
4219                 }
4220         }
4221
4222         macro_rules! sign_msg {
4223                 ($unsigned_msg: expr) => {
4224                         let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
4225                         let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_local_keys().inner.funding_key);
4226                         let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_local_keys().inner.funding_key);
4227                         let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
4228                         let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
4229                         chan_announcement = msgs::ChannelAnnouncement {
4230                                 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
4231                                 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
4232                                 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
4233                                 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
4234                                 contents: $unsigned_msg
4235                         }
4236                 }
4237         }
4238
4239         let unsigned_msg = dummy_unsigned_msg!();
4240         sign_msg!(unsigned_msg);
4241         assert_eq!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap(), true);
4242         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 } );
4243
4244         // Configured with Network::Testnet
4245         let mut unsigned_msg = dummy_unsigned_msg!();
4246         unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.bitcoin_hash();
4247         sign_msg!(unsigned_msg);
4248         assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4249
4250         let mut unsigned_msg = dummy_unsigned_msg!();
4251         unsigned_msg.chain_hash = BlockHash::hash(&[1,2,3,4,5,6,7,8,9]);
4252         sign_msg!(unsigned_msg);
4253         assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4254 }
4255
4256 #[test]
4257 fn test_no_txn_manager_serialize_deserialize() {
4258         let chanmon_cfgs = create_chanmon_cfgs(2);
4259         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4260         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4261         let logger: test_utils::TestLogger;
4262         let fee_estimator: test_utils::TestFeeEstimator;
4263         let new_chain_monitor: test_utils::TestChainMonitor;
4264         let keys_manager: test_utils::TestKeysInterface;
4265         let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4266         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4267
4268         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4269
4270         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4271
4272         let nodes_0_serialized = nodes[0].node.encode();
4273         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4274         nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
4275
4276         logger = test_utils::TestLogger::new();
4277         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4278         new_chain_monitor = test_utils::TestChainMonitor::new(nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator);
4279         nodes[0].chain_monitor = &new_chain_monitor;
4280         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4281         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read).unwrap();
4282         assert!(chan_0_monitor_read.is_empty());
4283
4284         let mut nodes_0_read = &nodes_0_serialized[..];
4285         let config = UserConfig::default();
4286         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4287         let (_, nodes_0_deserialized_tmp) = {
4288                 let mut channel_monitors = HashMap::new();
4289                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4290                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4291                         default_config: config,
4292                         keys_manager: &keys_manager,
4293                         fee_estimator: &fee_estimator,
4294                         chain_monitor: nodes[0].chain_monitor,
4295                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4296                         logger: &logger,
4297                         channel_monitors: &mut channel_monitors,
4298                 }).unwrap()
4299         };
4300         nodes_0_deserialized = nodes_0_deserialized_tmp;
4301         assert!(nodes_0_read.is_empty());
4302
4303         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4304         nodes[0].node = &nodes_0_deserialized;
4305         assert_eq!(nodes[0].node.list_channels().len(), 1);
4306         check_added_monitors!(nodes[0], 1);
4307
4308         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4309         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4310         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4311         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4312
4313         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4314         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4315         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4316         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4317
4318         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4319         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4320         for node in nodes.iter() {
4321                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4322                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4323                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4324         }
4325
4326         send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4327 }
4328
4329 #[test]
4330 fn test_manager_serialize_deserialize_events() {
4331         // This test makes sure the events field in ChannelManager survives de/serialization
4332         let chanmon_cfgs = create_chanmon_cfgs(2);
4333         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4334         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4335         let fee_estimator: test_utils::TestFeeEstimator;
4336         let logger: test_utils::TestLogger;
4337         let new_chain_monitor: test_utils::TestChainMonitor;
4338         let keys_manager: test_utils::TestKeysInterface;
4339         let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4340         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4341
4342         // Start creating a channel, but stop right before broadcasting the event message FundingBroadcastSafe
4343         let channel_value = 100000;
4344         let push_msat = 10001;
4345         let a_flags = InitFeatures::known();
4346         let b_flags = InitFeatures::known();
4347         let node_a = nodes.pop().unwrap();
4348         let node_b = nodes.pop().unwrap();
4349         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4350         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()));
4351         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()));
4352
4353         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4354
4355         node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
4356         check_added_monitors!(node_a, 0);
4357
4358         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()));
4359         {
4360                 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4361                 assert_eq!(added_monitors.len(), 1);
4362                 assert_eq!(added_monitors[0].0, funding_output);
4363                 added_monitors.clear();
4364         }
4365
4366         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()));
4367         {
4368                 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4369                 assert_eq!(added_monitors.len(), 1);
4370                 assert_eq!(added_monitors[0].0, funding_output);
4371                 added_monitors.clear();
4372         }
4373         // Normally, this is where node_a would check for a FundingBroadcastSafe event, but the test de/serializes first instead
4374
4375         nodes.push(node_a);
4376         nodes.push(node_b);
4377
4378         // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4379         let nodes_0_serialized = nodes[0].node.encode();
4380         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4381         nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
4382
4383         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4384         logger = test_utils::TestLogger::new();
4385         new_chain_monitor = test_utils::TestChainMonitor::new(nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator);
4386         nodes[0].chain_monitor = &new_chain_monitor;
4387         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4388         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read).unwrap();
4389         assert!(chan_0_monitor_read.is_empty());
4390
4391         let mut nodes_0_read = &nodes_0_serialized[..];
4392         let config = UserConfig::default();
4393         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4394         let (_, nodes_0_deserialized_tmp) = {
4395                 let mut channel_monitors = HashMap::new();
4396                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4397                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4398                         default_config: config,
4399                         keys_manager: &keys_manager,
4400                         fee_estimator: &fee_estimator,
4401                         chain_monitor: nodes[0].chain_monitor,
4402                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4403                         logger: &logger,
4404                         channel_monitors: &mut channel_monitors,
4405                 }).unwrap()
4406         };
4407         nodes_0_deserialized = nodes_0_deserialized_tmp;
4408         assert!(nodes_0_read.is_empty());
4409
4410         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4411
4412         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4413         nodes[0].node = &nodes_0_deserialized;
4414
4415         // After deserializing, make sure the FundingBroadcastSafe event is still held by the channel manager
4416         let events_4 = nodes[0].node.get_and_clear_pending_events();
4417         assert_eq!(events_4.len(), 1);
4418         match events_4[0] {
4419                 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
4420                         assert_eq!(user_channel_id, 42);
4421                         assert_eq!(*funding_txo, funding_output);
4422                 },
4423                 _ => panic!("Unexpected event"),
4424         };
4425
4426         // Make sure the channel is functioning as though the de/serialization never happened
4427         assert_eq!(nodes[0].node.list_channels().len(), 1);
4428         check_added_monitors!(nodes[0], 1);
4429
4430         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4431         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4432         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4433         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4434
4435         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4436         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4437         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4438         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4439
4440         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4441         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4442         for node in nodes.iter() {
4443                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4444                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4445                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4446         }
4447
4448         send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4449 }
4450
4451 #[test]
4452 fn test_simple_manager_serialize_deserialize() {
4453         let chanmon_cfgs = create_chanmon_cfgs(2);
4454         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4455         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4456         let logger: test_utils::TestLogger;
4457         let fee_estimator: test_utils::TestFeeEstimator;
4458         let new_chain_monitor: test_utils::TestChainMonitor;
4459         let keys_manager: test_utils::TestKeysInterface;
4460         let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4461         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4462         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4463
4464         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4465         let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4466
4467         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4468
4469         let nodes_0_serialized = nodes[0].node.encode();
4470         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4471         nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
4472
4473         logger = test_utils::TestLogger::new();
4474         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4475         new_chain_monitor = test_utils::TestChainMonitor::new(nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator);
4476         nodes[0].chain_monitor = &new_chain_monitor;
4477         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4478         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read).unwrap();
4479         assert!(chan_0_monitor_read.is_empty());
4480
4481         let mut nodes_0_read = &nodes_0_serialized[..];
4482         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4483         let (_, nodes_0_deserialized_tmp) = {
4484                 let mut channel_monitors = HashMap::new();
4485                 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4486                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4487                         default_config: UserConfig::default(),
4488                         keys_manager: &keys_manager,
4489                         fee_estimator: &fee_estimator,
4490                         chain_monitor: nodes[0].chain_monitor,
4491                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4492                         logger: &logger,
4493                         channel_monitors: &mut channel_monitors,
4494                 }).unwrap()
4495         };
4496         nodes_0_deserialized = nodes_0_deserialized_tmp;
4497         assert!(nodes_0_read.is_empty());
4498
4499         assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4500         nodes[0].node = &nodes_0_deserialized;
4501         check_added_monitors!(nodes[0], 1);
4502
4503         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4504
4505         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4506         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage, 1_000_000);
4507 }
4508
4509 #[test]
4510 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4511         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4512         let chanmon_cfgs = create_chanmon_cfgs(4);
4513         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4514         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4515         let logger: test_utils::TestLogger;
4516         let fee_estimator: test_utils::TestFeeEstimator;
4517         let new_chain_monitor: test_utils::TestChainMonitor;
4518         let keys_manager: test_utils::TestKeysInterface;
4519         let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4520         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4521         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4522         create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known());
4523         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4524
4525         let mut node_0_stale_monitors_serialized = Vec::new();
4526         for monitor in nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter() {
4527                 let mut writer = test_utils::TestVecWriter(Vec::new());
4528                 monitor.1.write_for_disk(&mut writer).unwrap();
4529                 node_0_stale_monitors_serialized.push(writer.0);
4530         }
4531
4532         let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4533
4534         // Serialize the ChannelManager here, but the monitor we keep up-to-date
4535         let nodes_0_serialized = nodes[0].node.encode();
4536
4537         route_payment(&nodes[0], &[&nodes[3]], 1000000);
4538         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4539         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4540         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4541
4542         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4543         // nodes[3])
4544         let mut node_0_monitors_serialized = Vec::new();
4545         for monitor in nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter() {
4546                 let mut writer = test_utils::TestVecWriter(Vec::new());
4547                 monitor.1.write_for_disk(&mut writer).unwrap();
4548                 node_0_monitors_serialized.push(writer.0);
4549         }
4550
4551         logger = test_utils::TestLogger::new();
4552         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4553         new_chain_monitor = test_utils::TestChainMonitor::new(nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator);
4554         nodes[0].chain_monitor = &new_chain_monitor;
4555
4556         let mut node_0_stale_monitors = Vec::new();
4557         for serialized in node_0_stale_monitors_serialized.iter() {
4558                 let mut read = &serialized[..];
4559                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read).unwrap();
4560                 assert!(read.is_empty());
4561                 node_0_stale_monitors.push(monitor);
4562         }
4563
4564         let mut node_0_monitors = Vec::new();
4565         for serialized in node_0_monitors_serialized.iter() {
4566                 let mut read = &serialized[..];
4567                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read).unwrap();
4568                 assert!(read.is_empty());
4569                 node_0_monitors.push(monitor);
4570         }
4571
4572         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4573
4574         let mut nodes_0_read = &nodes_0_serialized[..];
4575         if let Err(msgs::DecodeError::InvalidValue) =
4576                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4577                 default_config: UserConfig::default(),
4578                 keys_manager: &keys_manager,
4579                 fee_estimator: &fee_estimator,
4580                 chain_monitor: nodes[0].chain_monitor,
4581                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4582                 logger: &logger,
4583                 channel_monitors: &mut node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4584         }) { } else {
4585                 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4586         };
4587
4588         let mut nodes_0_read = &nodes_0_serialized[..];
4589         let (_, nodes_0_deserialized_tmp) =
4590                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4591                 default_config: UserConfig::default(),
4592                 keys_manager: &keys_manager,
4593                 fee_estimator: &fee_estimator,
4594                 chain_monitor: nodes[0].chain_monitor,
4595                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4596                 logger: &logger,
4597                 channel_monitors: &mut node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4598         }).unwrap();
4599         nodes_0_deserialized = nodes_0_deserialized_tmp;
4600         assert!(nodes_0_read.is_empty());
4601
4602         { // Channel close should result in a commitment tx and an HTLC tx
4603                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4604                 assert_eq!(txn.len(), 2);
4605                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4606                 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
4607         }
4608
4609         for monitor in node_0_monitors.drain(..) {
4610                 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4611                 check_added_monitors!(nodes[0], 1);
4612         }
4613         nodes[0].node = &nodes_0_deserialized;
4614
4615         // nodes[1] and nodes[2] have no lost state with nodes[0]...
4616         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4617         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4618         //... and we can even still claim the payment!
4619         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage, 1_000_000);
4620
4621         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4622         let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4623         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4624         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4625         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4626         assert_eq!(msg_events.len(), 1);
4627         if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4628                 match action {
4629                         &ErrorAction::SendErrorMessage { ref msg } => {
4630                                 assert_eq!(msg.channel_id, channel_id);
4631                         },
4632                         _ => panic!("Unexpected event!"),
4633                 }
4634         }
4635 }
4636
4637 macro_rules! check_spendable_outputs {
4638         ($node: expr, $der_idx: expr, $keysinterface: expr, $chan_value: expr) => {
4639                 {
4640                         let events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4641                         let mut txn = Vec::new();
4642                         for event in events {
4643                                 match event {
4644                                         Event::SpendableOutputs { ref outputs } => {
4645                                                 for outp in outputs {
4646                                                         match *outp {
4647                                                                 SpendableOutputDescriptor::StaticOutputRemotePayment { ref outpoint, ref output, ref key_derivation_params } => {
4648                                                                         let input = TxIn {
4649                                                                                 previous_output: outpoint.clone(),
4650                                                                                 script_sig: Script::new(),
4651                                                                                 sequence: 0,
4652                                                                                 witness: Vec::new(),
4653                                                                         };
4654                                                                         let outp = TxOut {
4655                                                                                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4656                                                                                 value: output.value,
4657                                                                         };
4658                                                                         let mut spend_tx = Transaction {
4659                                                                                 version: 2,
4660                                                                                 lock_time: 0,
4661                                                                                 input: vec![input],
4662                                                                                 output: vec![outp],
4663                                                                         };
4664                                                                         let secp_ctx = Secp256k1::new();
4665                                                                         let keys = $keysinterface.derive_channel_keys($chan_value, key_derivation_params.0, key_derivation_params.1);
4666                                                                         let remotepubkey = keys.pubkeys().payment_point;
4667                                                                         let witness_script = Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: remotepubkey}, Network::Testnet).script_pubkey();
4668                                                                         let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
4669                                                                         let remotesig = secp_ctx.sign(&sighash, &keys.inner.payment_key);
4670                                                                         spend_tx.input[0].witness.push(remotesig.serialize_der().to_vec());
4671                                                                         spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4672                                                                         spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
4673                                                                         txn.push(spend_tx);
4674                                                                 },
4675                                                                 SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref per_commitment_point, ref to_self_delay, ref output, ref key_derivation_params, ref remote_revocation_pubkey } => {
4676                                                                         let input = TxIn {
4677                                                                                 previous_output: outpoint.clone(),
4678                                                                                 script_sig: Script::new(),
4679                                                                                 sequence: *to_self_delay as u32,
4680                                                                                 witness: Vec::new(),
4681                                                                         };
4682                                                                         let outp = TxOut {
4683                                                                                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4684                                                                                 value: output.value,
4685                                                                         };
4686                                                                         let mut spend_tx = Transaction {
4687                                                                                 version: 2,
4688                                                                                 lock_time: 0,
4689                                                                                 input: vec![input],
4690                                                                                 output: vec![outp],
4691                                                                         };
4692                                                                         let secp_ctx = Secp256k1::new();
4693                                                                         let keys = $keysinterface.derive_channel_keys($chan_value, key_derivation_params.0, key_derivation_params.1);
4694                                                                         if let Ok(delayed_payment_key) = chan_utils::derive_private_key(&secp_ctx, &per_commitment_point, &keys.inner.delayed_payment_base_key) {
4695
4696                                                                                 let delayed_payment_pubkey = PublicKey::from_secret_key(&secp_ctx, &delayed_payment_key);
4697                                                                                 let witness_script = chan_utils::get_revokeable_redeemscript(remote_revocation_pubkey, *to_self_delay, &delayed_payment_pubkey);
4698                                                                                 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
4699                                                                                 let local_delayedsig = secp_ctx.sign(&sighash, &delayed_payment_key);
4700                                                                                 spend_tx.input[0].witness.push(local_delayedsig.serialize_der().to_vec());
4701                                                                                 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4702                                                                                 spend_tx.input[0].witness.push(vec!()); //MINIMALIF
4703                                                                                 spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
4704                                                                         } else { panic!() }
4705                                                                         txn.push(spend_tx);
4706                                                                 },
4707                                                                 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
4708                                                                         let secp_ctx = Secp256k1::new();
4709                                                                         let input = TxIn {
4710                                                                                 previous_output: outpoint.clone(),
4711                                                                                 script_sig: Script::new(),
4712                                                                                 sequence: 0,
4713                                                                                 witness: Vec::new(),
4714                                                                         };
4715                                                                         let outp = TxOut {
4716                                                                                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4717                                                                                 value: output.value,
4718                                                                         };
4719                                                                         let mut spend_tx = Transaction {
4720                                                                                 version: 2,
4721                                                                                 lock_time: 0,
4722                                                                                 input: vec![input],
4723                                                                                 output: vec![outp.clone()],
4724                                                                         };
4725                                                                         let secret = {
4726                                                                                 match ExtendedPrivKey::new_master(Network::Testnet, &$node.node_seed) {
4727                                                                                         Ok(master_key) => {
4728                                                                                                 match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx).expect("key space exhausted")) {
4729                                                                                                         Ok(key) => key,
4730                                                                                                         Err(_) => panic!("Your RNG is busted"),
4731                                                                                                 }
4732                                                                                         }
4733                                                                                         Err(_) => panic!("Your rng is busted"),
4734                                                                                 }
4735                                                                         };
4736                                                                         let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
4737                                                                         let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
4738                                                                         let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
4739                                                                         let sig = secp_ctx.sign(&sighash, &secret.private_key.key);
4740                                                                         spend_tx.input[0].witness.push(sig.serialize_der().to_vec());
4741                                                                         spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4742                                                                         spend_tx.input[0].witness.push(pubkey.key.serialize().to_vec());
4743                                                                         txn.push(spend_tx);
4744                                                                 },
4745                                                         }
4746                                                 }
4747                                         },
4748                                         _ => panic!("Unexpected event"),
4749                                 };
4750                         }
4751                         txn
4752                 }
4753         }
4754 }
4755
4756 #[test]
4757 fn test_claim_sizeable_push_msat() {
4758         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4759         let chanmon_cfgs = create_chanmon_cfgs(2);
4760         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4761         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4762         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4763
4764         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4765         nodes[1].node.force_close_channel(&chan.2);
4766         check_closed_broadcast!(nodes[1], false);
4767         check_added_monitors!(nodes[1], 1);
4768         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4769         assert_eq!(node_txn.len(), 1);
4770         check_spends!(node_txn[0], chan.3);
4771         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
4772
4773         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4774         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4775         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4776
4777         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4778         assert_eq!(spend_txn.len(), 1);
4779         check_spends!(spend_txn[0], node_txn[0]);
4780 }
4781
4782 #[test]
4783 fn test_claim_on_remote_sizeable_push_msat() {
4784         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4785         // to_remote output is encumbered by a P2WPKH
4786         let chanmon_cfgs = create_chanmon_cfgs(2);
4787         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4788         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4789         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4790
4791         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4792         nodes[0].node.force_close_channel(&chan.2);
4793         check_closed_broadcast!(nodes[0], false);
4794         check_added_monitors!(nodes[0], 1);
4795
4796         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4797         assert_eq!(node_txn.len(), 1);
4798         check_spends!(node_txn[0], chan.3);
4799         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
4800
4801         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4802         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4803         check_closed_broadcast!(nodes[1], false);
4804         check_added_monitors!(nodes[1], 1);
4805         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4806
4807         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4808         assert_eq!(spend_txn.len(), 2);
4809         assert_eq!(spend_txn[0], spend_txn[1]);
4810         check_spends!(spend_txn[0], node_txn[0]);
4811 }
4812
4813 #[test]
4814 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4815         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4816         // to_remote output is encumbered by a P2WPKH
4817
4818         let chanmon_cfgs = create_chanmon_cfgs(2);
4819         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4820         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4821         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4822
4823         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4824         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4825         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4826         assert_eq!(revoked_local_txn[0].input.len(), 1);
4827         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4828
4829         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4830         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4831         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
4832         check_closed_broadcast!(nodes[1], false);
4833         check_added_monitors!(nodes[1], 1);
4834
4835         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4836         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4837         connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4838         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4839
4840         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4841         assert_eq!(spend_txn.len(), 3);
4842         assert_eq!(spend_txn[0], spend_txn[1]); // to_remote output on revoked remote commitment_tx
4843         check_spends!(spend_txn[0], revoked_local_txn[0]);
4844         check_spends!(spend_txn[2], node_txn[0]);
4845 }
4846
4847 #[test]
4848 fn test_static_spendable_outputs_preimage_tx() {
4849         let chanmon_cfgs = create_chanmon_cfgs(2);
4850         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4851         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4852         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4853
4854         // Create some initial channels
4855         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4856
4857         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4858
4859         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4860         assert_eq!(commitment_tx[0].input.len(), 1);
4861         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4862
4863         // Settle A's commitment tx on B's chain
4864         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4865         assert!(nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000));
4866         check_added_monitors!(nodes[1], 1);
4867         connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
4868         check_added_monitors!(nodes[1], 1);
4869         let events = nodes[1].node.get_and_clear_pending_msg_events();
4870         match events[0] {
4871                 MessageSendEvent::UpdateHTLCs { .. } => {},
4872                 _ => panic!("Unexpected event"),
4873         }
4874         match events[1] {
4875                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4876                 _ => panic!("Unexepected event"),
4877         }
4878
4879         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4880         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4881         assert_eq!(node_txn.len(), 3);
4882         check_spends!(node_txn[0], commitment_tx[0]);
4883         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4884         check_spends!(node_txn[1], chan_1.3);
4885         check_spends!(node_txn[2], node_txn[1]);
4886
4887         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4888         connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4889         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4890
4891         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4892         assert_eq!(spend_txn.len(), 1);
4893         check_spends!(spend_txn[0], node_txn[0]);
4894 }
4895
4896 #[test]
4897 fn test_static_spendable_outputs_timeout_tx() {
4898         let chanmon_cfgs = create_chanmon_cfgs(2);
4899         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4900         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4901         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4902
4903         // Create some initial channels
4904         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4905
4906         // Rebalance the network a bit by relaying one payment through all the channels ...
4907         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
4908
4909         let (_, our_payment_hash) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4910
4911         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4912         assert_eq!(commitment_tx[0].input.len(), 1);
4913         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4914
4915         // Settle A's commitment tx on B' chain
4916         let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
4917         connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()] }, 0);
4918         check_added_monitors!(nodes[1], 1);
4919         let events = nodes[1].node.get_and_clear_pending_msg_events();
4920         match events[0] {
4921                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4922                 _ => panic!("Unexpected event"),
4923         }
4924
4925         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4926         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4927         assert_eq!(node_txn.len(), 3); // ChannelManager : 2 (local commitent tx + HTLC-timeout), ChannelMonitor: timeout tx
4928         check_spends!(node_txn[0],  commitment_tx[0].clone());
4929         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4930         check_spends!(node_txn[1], chan_1.3.clone());
4931         check_spends!(node_txn[2], node_txn[1]);
4932
4933         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4934         connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4935         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4936         expect_payment_failed!(nodes[1], our_payment_hash, true);
4937
4938         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4939         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote (*2), timeout_tx.output (*1)
4940         check_spends!(spend_txn[2], node_txn[0].clone());
4941 }
4942
4943 #[test]
4944 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4945         let chanmon_cfgs = create_chanmon_cfgs(2);
4946         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4947         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4948         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4949
4950         // Create some initial channels
4951         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4952
4953         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4954         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4955         assert_eq!(revoked_local_txn[0].input.len(), 1);
4956         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4957
4958         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4959
4960         let  header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4961         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
4962         check_closed_broadcast!(nodes[1], false);
4963         check_added_monitors!(nodes[1], 1);
4964
4965         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4966         assert_eq!(node_txn.len(), 2);
4967         assert_eq!(node_txn[0].input.len(), 2);
4968         check_spends!(node_txn[0], revoked_local_txn[0]);
4969
4970         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4971         connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4972         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4973
4974         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4975         assert_eq!(spend_txn.len(), 1);
4976         check_spends!(spend_txn[0], node_txn[0]);
4977 }
4978
4979 #[test]
4980 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4981         let chanmon_cfgs = create_chanmon_cfgs(2);
4982         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4983         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4984         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4985
4986         // Create some initial channels
4987         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4988
4989         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4990         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4991         assert_eq!(revoked_local_txn[0].input.len(), 1);
4992         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4993
4994         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4995
4996         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4997         // A will generate HTLC-Timeout from revoked commitment tx
4998         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4999         check_closed_broadcast!(nodes[0], false);
5000         check_added_monitors!(nodes[0], 1);
5001
5002         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5003         assert_eq!(revoked_htlc_txn.len(), 2);
5004         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5005         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5006         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5007         check_spends!(revoked_htlc_txn[1], chan_1.3);
5008
5009         // B will generate justice tx from A's revoked commitment/HTLC tx
5010         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 0);
5011         check_closed_broadcast!(nodes[1], false);
5012         check_added_monitors!(nodes[1], 1);
5013
5014         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5015         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
5016         assert_eq!(node_txn[0].input.len(), 2);
5017         check_spends!(node_txn[0], revoked_local_txn[0]);
5018         assert_eq!(node_txn[1].input.len(), 1);
5019         check_spends!(node_txn[1], revoked_htlc_txn[0]);
5020         assert_eq!(node_txn[2].input.len(), 1);
5021         check_spends!(node_txn[2], revoked_local_txn[0]);
5022         check_spends!(node_txn[3], chan_1.3);
5023
5024         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5025         connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone(), node_txn[2].clone()] }, 1);
5026         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
5027
5028         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
5029         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5030         assert_eq!(spend_txn.len(), 2);
5031         check_spends!(spend_txn[0], node_txn[0]);
5032         check_spends!(spend_txn[1], node_txn[2]);
5033 }
5034
5035 #[test]
5036 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
5037         let chanmon_cfgs = create_chanmon_cfgs(2);
5038         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5039         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5040         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5041
5042         // Create some initial channels
5043         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5044
5045         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5046         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5047         assert_eq!(revoked_local_txn[0].input.len(), 1);
5048         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5049
5050         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
5051
5052         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5053         // B will generate HTLC-Success from revoked commitment tx
5054         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5055         check_closed_broadcast!(nodes[1], false);
5056         check_added_monitors!(nodes[1], 1);
5057         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5058
5059         assert_eq!(revoked_htlc_txn.len(), 2);
5060         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5061         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5062         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5063
5064         // A will generate justice tx from B's revoked commitment/HTLC tx
5065         connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
5066         check_closed_broadcast!(nodes[0], false);
5067         check_added_monitors!(nodes[0], 1);
5068
5069         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5070         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5071         assert_eq!(node_txn[1].input.len(), 1);
5072         check_spends!(node_txn[1], revoked_htlc_txn[0]);
5073
5074         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5075         connect_block(&nodes[0], &Block { header: header_1, txdata: vec![node_txn[0].clone(), node_txn[2].clone()] }, 1);
5076         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
5077
5078         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5079         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5080         assert_eq!(spend_txn.len(), 5); // Duplicated SpendableOutput due to block rescan after revoked htlc output tracking
5081         assert_eq!(spend_txn[0], spend_txn[1]);
5082         assert_eq!(spend_txn[0], spend_txn[2]);
5083         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5084         check_spends!(spend_txn[3], node_txn[0]); // spending justice tx output from revoked local tx htlc received output
5085         check_spends!(spend_txn[4], node_txn[2]); // spending justice tx output on htlc success tx
5086 }
5087
5088 #[test]
5089 fn test_onchain_to_onchain_claim() {
5090         // Test that in case of channel closure, we detect the state of output and claim HTLC
5091         // on downstream peer's remote commitment tx.
5092         // First, have C claim an HTLC against its own latest commitment transaction.
5093         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5094         // channel.
5095         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5096         // gets broadcast.
5097
5098         let chanmon_cfgs = create_chanmon_cfgs(3);
5099         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5100         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5101         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5102
5103         // Create some initial channels
5104         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5105         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5106
5107         // Rebalance the network a bit by relaying one payment through all the channels ...
5108         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5109         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5110
5111         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5112         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5113         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5114         check_spends!(commitment_tx[0], chan_2.3);
5115         nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000);
5116         check_added_monitors!(nodes[2], 1);
5117         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5118         assert!(updates.update_add_htlcs.is_empty());
5119         assert!(updates.update_fail_htlcs.is_empty());
5120         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5121         assert!(updates.update_fail_malformed_htlcs.is_empty());
5122
5123         connect_block(&nodes[2], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
5124         check_closed_broadcast!(nodes[2], false);
5125         check_added_monitors!(nodes[2], 1);
5126
5127         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5128         assert_eq!(c_txn.len(), 3);
5129         assert_eq!(c_txn[0], c_txn[2]);
5130         assert_eq!(commitment_tx[0], c_txn[1]);
5131         check_spends!(c_txn[1], chan_2.3);
5132         check_spends!(c_txn[2], c_txn[1]);
5133         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5134         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5135         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5136         assert_eq!(c_txn[0].lock_time, 0); // Success tx
5137
5138         // 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
5139         connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
5140         {
5141                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5142                 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-timeout tx
5143                 assert_eq!(b_txn.len(), 3);
5144                 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
5145                 check_spends!(b_txn[2], b_txn[1]); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
5146                 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5147                 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5148                 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5149                 check_spends!(b_txn[0], c_txn[1]); // timeout tx on C remote commitment tx, issued by ChannelMonitor, * 2 due to block rescan
5150                 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5151                 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5152                 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5153                 b_txn.clear();
5154         }
5155         check_added_monitors!(nodes[1], 1);
5156         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5157         check_added_monitors!(nodes[1], 1);
5158         match msg_events[0] {
5159                 MessageSendEvent::BroadcastChannelUpdate {  .. } => {},
5160                 _ => panic!("Unexpected event"),
5161         }
5162         match msg_events[1] {
5163                 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, .. } } => {
5164                         assert!(update_add_htlcs.is_empty());
5165                         assert!(update_fail_htlcs.is_empty());
5166                         assert_eq!(update_fulfill_htlcs.len(), 1);
5167                         assert!(update_fail_malformed_htlcs.is_empty());
5168                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5169                 },
5170                 _ => panic!("Unexpected event"),
5171         };
5172         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5173         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5174         connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
5175         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5176         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5177         assert_eq!(b_txn.len(), 3);
5178         check_spends!(b_txn[1], chan_1.3);
5179         check_spends!(b_txn[2], b_txn[1]);
5180         check_spends!(b_txn[0], commitment_tx[0]);
5181         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5182         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5183         assert_eq!(b_txn[0].lock_time, 0); // Success tx
5184
5185         check_closed_broadcast!(nodes[1], false);
5186         check_added_monitors!(nodes[1], 1);
5187 }
5188
5189 #[test]
5190 fn test_duplicate_payment_hash_one_failure_one_success() {
5191         // Topology : A --> B --> C
5192         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5193         let chanmon_cfgs = create_chanmon_cfgs(3);
5194         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5195         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5196         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5197
5198         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5199         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5200
5201         let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5202         *nodes[0].network_payment_count.borrow_mut() -= 1;
5203         assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
5204
5205         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5206         assert_eq!(commitment_txn[0].input.len(), 1);
5207         check_spends!(commitment_txn[0], chan_2.3);
5208
5209         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5210         connect_block(&nodes[1], &Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
5211         check_closed_broadcast!(nodes[1], false);
5212         check_added_monitors!(nodes[1], 1);
5213
5214         let htlc_timeout_tx;
5215         { // Extract one of the two HTLC-Timeout transaction
5216                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5217                 // ChannelMonitor: timeout tx * 2, ChannelManager: local commitment tx + HTLC-timeout * 2
5218                 assert_eq!(node_txn.len(), 5);
5219                 check_spends!(node_txn[0], commitment_txn[0]);
5220                 assert_eq!(node_txn[0].input.len(), 1);
5221                 check_spends!(node_txn[1], commitment_txn[0]);
5222                 assert_eq!(node_txn[1].input.len(), 1);
5223                 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
5224                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5225                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5226                 check_spends!(node_txn[2], chan_2.3);
5227                 check_spends!(node_txn[3], node_txn[2]);
5228                 check_spends!(node_txn[4], node_txn[2]);
5229                 htlc_timeout_tx = node_txn[1].clone();
5230         }
5231
5232         nodes[2].node.claim_funds(our_payment_preimage, &None, 900_000);
5233         connect_block(&nodes[2], &Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
5234         check_added_monitors!(nodes[2], 3);
5235         let events = nodes[2].node.get_and_clear_pending_msg_events();
5236         match events[0] {
5237                 MessageSendEvent::UpdateHTLCs { .. } => {},
5238                 _ => panic!("Unexpected event"),
5239         }
5240         match events[1] {
5241                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5242                 _ => panic!("Unexepected event"),
5243         }
5244         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5245         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)
5246         check_spends!(htlc_success_txn[2], chan_2.3);
5247         check_spends!(htlc_success_txn[3], htlc_success_txn[2]);
5248         check_spends!(htlc_success_txn[4], htlc_success_txn[2]);
5249         assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
5250         assert_eq!(htlc_success_txn[0].input.len(), 1);
5251         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5252         assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
5253         assert_eq!(htlc_success_txn[1].input.len(), 1);
5254         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5255         assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
5256         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5257         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5258
5259         connect_block(&nodes[1], &Block { header, txdata: vec![htlc_timeout_tx] }, 200);
5260         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 200, true, header.bitcoin_hash());
5261         expect_pending_htlcs_forwardable!(nodes[1]);
5262         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5263         assert!(htlc_updates.update_add_htlcs.is_empty());
5264         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5265         assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
5266         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5267         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5268         check_added_monitors!(nodes[1], 1);
5269
5270         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5271         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5272         {
5273                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5274                 let events = nodes[0].node.get_and_clear_pending_msg_events();
5275                 assert_eq!(events.len(), 1);
5276                 match events[0] {
5277                         MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. }  } => {
5278                         },
5279                         _ => { panic!("Unexpected event"); }
5280                 }
5281         }
5282         expect_payment_failed!(nodes[0], duplicate_payment_hash, false);
5283
5284         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5285         connect_block(&nodes[1], &Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
5286         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5287         assert!(updates.update_add_htlcs.is_empty());
5288         assert!(updates.update_fail_htlcs.is_empty());
5289         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5290         assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
5291         assert!(updates.update_fail_malformed_htlcs.is_empty());
5292         check_added_monitors!(nodes[1], 1);
5293
5294         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5295         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5296
5297         let events = nodes[0].node.get_and_clear_pending_events();
5298         match events[0] {
5299                 Event::PaymentSent { ref payment_preimage } => {
5300                         assert_eq!(*payment_preimage, our_payment_preimage);
5301                 }
5302                 _ => panic!("Unexpected event"),
5303         }
5304 }
5305
5306 #[test]
5307 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5308         let chanmon_cfgs = create_chanmon_cfgs(2);
5309         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5310         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5311         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5312
5313         // Create some initial channels
5314         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5315
5316         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5317         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5318         assert_eq!(local_txn[0].input.len(), 1);
5319         check_spends!(local_txn[0], chan_1.3);
5320
5321         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5322         nodes[1].node.claim_funds(payment_preimage, &None, 9_000_000);
5323         check_added_monitors!(nodes[1], 1);
5324         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5325         connect_block(&nodes[1], &Block { header, txdata: vec![local_txn[0].clone()] }, 1);
5326         check_added_monitors!(nodes[1], 1);
5327         let events = nodes[1].node.get_and_clear_pending_msg_events();
5328         match events[0] {
5329                 MessageSendEvent::UpdateHTLCs { .. } => {},
5330                 _ => panic!("Unexpected event"),
5331         }
5332         match events[1] {
5333                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5334                 _ => panic!("Unexepected event"),
5335         }
5336         let node_txn = {
5337                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5338                 assert_eq!(node_txn[0].input.len(), 1);
5339                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5340                 check_spends!(node_txn[0], local_txn[0]);
5341                 vec![node_txn[0].clone(), node_txn[2].clone()]
5342         };
5343
5344         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5345         connect_block(&nodes[1], &Block { header: header_201, txdata: node_txn.clone() }, 201);
5346         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 201, true, header_201.bitcoin_hash());
5347
5348         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5349         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5350         assert_eq!(spend_txn.len(), 2);
5351         check_spends!(spend_txn[0], node_txn[0]);
5352         check_spends!(spend_txn[1], node_txn[1]);
5353 }
5354
5355 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5356         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5357         // unrevoked commitment transaction.
5358         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5359         // a remote RAA before they could be failed backwards (and combinations thereof).
5360         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5361         // use the same payment hashes.
5362         // Thus, we use a six-node network:
5363         //
5364         // A \         / E
5365         //    - C - D -
5366         // B /         \ F
5367         // And test where C fails back to A/B when D announces its latest commitment transaction
5368         let chanmon_cfgs = create_chanmon_cfgs(6);
5369         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5370         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
5371         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5372         let logger = test_utils::TestLogger::new();
5373
5374         create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5375         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5376         let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5377         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5378         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5379
5380         // Rebalance and check output sanity...
5381         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000, 500_000);
5382         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000, 500_000);
5383         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5384
5385         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
5386         // 0th HTLC:
5387         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
5388         // 1st HTLC:
5389         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
5390         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
5391         let our_node_id = &nodes[1].node.get_our_node_id();
5392         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();
5393         // 2nd HTLC:
5394         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
5395         // 3rd HTLC:
5396         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
5397         // 4th HTLC:
5398         let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5399         // 5th HTLC:
5400         let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5401         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();
5402         // 6th HTLC:
5403         send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
5404         // 7th HTLC:
5405         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
5406
5407         // 8th HTLC:
5408         let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5409         // 9th HTLC:
5410         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();
5411         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
5412
5413         // 10th HTLC:
5414         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
5415         // 11th HTLC:
5416         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();
5417         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
5418
5419         // Double-check that six of the new HTLC were added
5420         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5421         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5422         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5423         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5424
5425         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5426         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5427         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1, &None));
5428         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3, &None));
5429         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5, &None));
5430         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6, &None));
5431         check_added_monitors!(nodes[4], 0);
5432         expect_pending_htlcs_forwardable!(nodes[4]);
5433         check_added_monitors!(nodes[4], 1);
5434
5435         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5436         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5437         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5438         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5439         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5440         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5441
5442         // Fail 3rd below-dust and 7th above-dust HTLCs
5443         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2, &None));
5444         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4, &None));
5445         check_added_monitors!(nodes[5], 0);
5446         expect_pending_htlcs_forwardable!(nodes[5]);
5447         check_added_monitors!(nodes[5], 1);
5448
5449         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5450         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5451         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5452         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5453
5454         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5455
5456         expect_pending_htlcs_forwardable!(nodes[3]);
5457         check_added_monitors!(nodes[3], 1);
5458         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5459         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5460         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5461         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5462         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5463         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5464         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5465         if deliver_last_raa {
5466                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5467         } else {
5468                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5469         }
5470
5471         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5472         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5473         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5474         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5475         //
5476         // We now broadcast the latest commitment transaction, which *should* result in failures for
5477         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5478         // the non-broadcast above-dust HTLCs.
5479         //
5480         // Alternatively, we may broadcast the previous commitment transaction, which should only
5481         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5482         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5483
5484         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5485         if announce_latest {
5486                 connect_block(&nodes[2], &Block { header, txdata: vec![ds_last_commitment_tx[0].clone()]}, 1);
5487         } else {
5488                 connect_block(&nodes[2], &Block { header, txdata: vec![ds_prev_commitment_tx[0].clone()]}, 1);
5489         }
5490         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1, 1, true,  header.bitcoin_hash());
5491         check_closed_broadcast!(nodes[2], false);
5492         expect_pending_htlcs_forwardable!(nodes[2]);
5493         check_added_monitors!(nodes[2], 3);
5494
5495         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5496         assert_eq!(cs_msgs.len(), 2);
5497         let mut a_done = false;
5498         for msg in cs_msgs {
5499                 match msg {
5500                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5501                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5502                                 // should be failed-backwards here.
5503                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5504                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5505                                         for htlc in &updates.update_fail_htlcs {
5506                                                 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 });
5507                                         }
5508                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5509                                         assert!(!a_done);
5510                                         a_done = true;
5511                                         &nodes[0]
5512                                 } else {
5513                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5514                                         for htlc in &updates.update_fail_htlcs {
5515                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5516                                         }
5517                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5518                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5519                                         &nodes[1]
5520                                 };
5521                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5522                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5523                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5524                                 if announce_latest {
5525                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5526                                         if *node_id == nodes[0].node.get_our_node_id() {
5527                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5528                                         }
5529                                 }
5530                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5531                         },
5532                         _ => panic!("Unexpected event"),
5533                 }
5534         }
5535
5536         let as_events = nodes[0].node.get_and_clear_pending_events();
5537         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5538         let mut as_failds = HashSet::new();
5539         for event in as_events.iter() {
5540                 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5541                         assert!(as_failds.insert(*payment_hash));
5542                         if *payment_hash != payment_hash_2 {
5543                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5544                         } else {
5545                                 assert!(!rejected_by_dest);
5546                         }
5547                 } else { panic!("Unexpected event"); }
5548         }
5549         assert!(as_failds.contains(&payment_hash_1));
5550         assert!(as_failds.contains(&payment_hash_2));
5551         if announce_latest {
5552                 assert!(as_failds.contains(&payment_hash_3));
5553                 assert!(as_failds.contains(&payment_hash_5));
5554         }
5555         assert!(as_failds.contains(&payment_hash_6));
5556
5557         let bs_events = nodes[1].node.get_and_clear_pending_events();
5558         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5559         let mut bs_failds = HashSet::new();
5560         for event in bs_events.iter() {
5561                 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5562                         assert!(bs_failds.insert(*payment_hash));
5563                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5564                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5565                         } else {
5566                                 assert!(!rejected_by_dest);
5567                         }
5568                 } else { panic!("Unexpected event"); }
5569         }
5570         assert!(bs_failds.contains(&payment_hash_1));
5571         assert!(bs_failds.contains(&payment_hash_2));
5572         if announce_latest {
5573                 assert!(bs_failds.contains(&payment_hash_4));
5574         }
5575         assert!(bs_failds.contains(&payment_hash_5));
5576
5577         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5578         // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
5579         // to unknown-preimage-etc, B should have gotten 2. Thus, in the
5580         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
5581         // PaymentFailureNetworkUpdates.
5582         let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
5583         assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5584         let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5585         assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5586         for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
5587                 match event {
5588                         &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
5589                         _ => panic!("Unexpected event"),
5590                 }
5591         }
5592 }
5593
5594 #[test]
5595 fn test_fail_backwards_latest_remote_announce_a() {
5596         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5597 }
5598
5599 #[test]
5600 fn test_fail_backwards_latest_remote_announce_b() {
5601         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5602 }
5603
5604 #[test]
5605 fn test_fail_backwards_previous_remote_announce() {
5606         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5607         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5608         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5609 }
5610
5611 #[test]
5612 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5613         let chanmon_cfgs = create_chanmon_cfgs(2);
5614         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5615         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5616         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5617
5618         // Create some initial channels
5619         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5620
5621         let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5622         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5623         assert_eq!(local_txn[0].input.len(), 1);
5624         check_spends!(local_txn[0], chan_1.3);
5625
5626         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5627         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5628         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] }, 200);
5629         check_closed_broadcast!(nodes[0], false);
5630         check_added_monitors!(nodes[0], 1);
5631
5632         let htlc_timeout = {
5633                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5634                 assert_eq!(node_txn[0].input.len(), 1);
5635                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5636                 check_spends!(node_txn[0], local_txn[0]);
5637                 node_txn[0].clone()
5638         };
5639
5640         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5641         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
5642         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 201, true, header_201.bitcoin_hash());
5643         expect_payment_failed!(nodes[0], our_payment_hash, true);
5644
5645         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5646         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5647         assert_eq!(spend_txn.len(), 3);
5648         assert_eq!(spend_txn[0], spend_txn[1]);
5649         check_spends!(spend_txn[0], local_txn[0]);
5650         check_spends!(spend_txn[2], htlc_timeout);
5651 }
5652
5653 #[test]
5654 fn test_key_derivation_params() {
5655         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5656         // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5657         // let us re-derive the channel key set to then derive a delayed_payment_key.
5658
5659         let chanmon_cfgs = create_chanmon_cfgs(3);
5660
5661         // We manually create the node configuration to backup the seed.
5662         let seed = [42; 32];
5663         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5664         let chain_monitor = test_utils::TestChainMonitor::new(&chanmon_cfgs[0].tx_broadcaster, &chanmon_cfgs[0].logger, &chanmon_cfgs[0].fee_estimator);
5665         let node = NodeCfg { chain_source: &chanmon_cfgs[0].chain_source, logger: &chanmon_cfgs[0].logger, tx_broadcaster: &chanmon_cfgs[0].tx_broadcaster, fee_estimator: &chanmon_cfgs[0].fee_estimator, chain_monitor, keys_manager, node_seed: seed };
5666         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5667         node_cfgs.remove(0);
5668         node_cfgs.insert(0, node);
5669
5670         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5671         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5672
5673         // Create some initial channels
5674         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5675         // for node 0
5676         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5677         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5678         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5679
5680         let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5681         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5682         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5683         assert_eq!(local_txn_1[0].input.len(), 1);
5684         check_spends!(local_txn_1[0], chan_1.3);
5685
5686         // We check funding pubkey are unique
5687         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]));
5688         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]));
5689         if from_0_funding_key_0 == from_1_funding_key_0
5690             || from_0_funding_key_0 == from_1_funding_key_1
5691             || from_0_funding_key_1 == from_1_funding_key_0
5692             || from_0_funding_key_1 == from_1_funding_key_1 {
5693                 panic!("Funding pubkeys aren't unique");
5694         }
5695
5696         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5697         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5698         connect_block(&nodes[0], &Block { header, txdata: vec![local_txn_1[0].clone()] }, 200);
5699         check_closed_broadcast!(nodes[0], false);
5700         check_added_monitors!(nodes[0], 1);
5701
5702         let htlc_timeout = {
5703                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5704                 assert_eq!(node_txn[0].input.len(), 1);
5705                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5706                 check_spends!(node_txn[0], local_txn_1[0]);
5707                 node_txn[0].clone()
5708         };
5709
5710         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5711         connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
5712         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 201, true, header_201.bitcoin_hash());
5713         expect_payment_failed!(nodes[0], our_payment_hash, true);
5714
5715         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5716         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5717         let spend_txn = check_spendable_outputs!(nodes[0], 1, new_keys_manager, 100000);
5718         assert_eq!(spend_txn.len(), 3);
5719         assert_eq!(spend_txn[0], spend_txn[1]);
5720         check_spends!(spend_txn[0], local_txn_1[0]);
5721         check_spends!(spend_txn[2], htlc_timeout);
5722 }
5723
5724 #[test]
5725 fn test_static_output_closing_tx() {
5726         let chanmon_cfgs = create_chanmon_cfgs(2);
5727         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5728         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5729         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5730
5731         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5732
5733         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
5734         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5735
5736         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5737         connect_block(&nodes[0], &Block { header, txdata: vec![closing_tx.clone()] }, 0);
5738         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 0, true, header.bitcoin_hash());
5739
5740         let spend_txn = check_spendable_outputs!(nodes[0], 2, node_cfgs[0].keys_manager, 100000);
5741         assert_eq!(spend_txn.len(), 1);
5742         check_spends!(spend_txn[0], closing_tx);
5743
5744         connect_block(&nodes[1], &Block { header, txdata: vec![closing_tx.clone()] }, 0);
5745         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 0, true, header.bitcoin_hash());
5746
5747         let spend_txn = check_spendable_outputs!(nodes[1], 2, node_cfgs[1].keys_manager, 100000);
5748         assert_eq!(spend_txn.len(), 1);
5749         check_spends!(spend_txn[0], closing_tx);
5750 }
5751
5752 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5753         let chanmon_cfgs = create_chanmon_cfgs(2);
5754         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5755         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5756         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5757         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5758
5759         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5760
5761         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5762         // present in B's local commitment transaction, but none of A's commitment transactions.
5763         assert!(nodes[1].node.claim_funds(our_payment_preimage, &None, if use_dust { 50_000 } else { 3_000_000 }));
5764         check_added_monitors!(nodes[1], 1);
5765
5766         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5767         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5768         let events = nodes[0].node.get_and_clear_pending_events();
5769         assert_eq!(events.len(), 1);
5770         match events[0] {
5771                 Event::PaymentSent { payment_preimage } => {
5772                         assert_eq!(payment_preimage, our_payment_preimage);
5773                 },
5774                 _ => panic!("Unexpected event"),
5775         }
5776
5777         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5778         check_added_monitors!(nodes[0], 1);
5779         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5780         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5781         check_added_monitors!(nodes[1], 1);
5782
5783         let mut block = Block {
5784                 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5785                 txdata: vec![],
5786         };
5787         for i in 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + CHAN_CONFIRM_DEPTH + 1 {
5788                 connect_block(&nodes[1], &block, i);
5789                 block.header.prev_blockhash = block.bitcoin_hash();
5790         }
5791         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5792         check_closed_broadcast!(nodes[1], false);
5793         check_added_monitors!(nodes[1], 1);
5794 }
5795
5796 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5797         let chanmon_cfgs = create_chanmon_cfgs(2);
5798         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5799         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5800         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5801         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5802         let logger = test_utils::TestLogger::new();
5803
5804         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5805         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5806         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();
5807         nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
5808         check_added_monitors!(nodes[0], 1);
5809
5810         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5811
5812         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5813         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5814         // to "time out" the HTLC.
5815
5816         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5817
5818         for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5819                 connect_block(&nodes[0], &Block { header, txdata: Vec::new()}, i);
5820                 header.prev_blockhash = header.bitcoin_hash();
5821         }
5822         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5823         check_closed_broadcast!(nodes[0], false);
5824         check_added_monitors!(nodes[0], 1);
5825 }
5826
5827 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5828         let chanmon_cfgs = create_chanmon_cfgs(3);
5829         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5830         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5831         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5832         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5833
5834         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5835         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5836         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5837         // actually revoked.
5838         let htlc_value = if use_dust { 50000 } else { 3000000 };
5839         let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5840         assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash, &None));
5841         expect_pending_htlcs_forwardable!(nodes[1]);
5842         check_added_monitors!(nodes[1], 1);
5843
5844         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5845         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5846         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5847         check_added_monitors!(nodes[0], 1);
5848         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5849         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5850         check_added_monitors!(nodes[1], 1);
5851         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5852         check_added_monitors!(nodes[1], 1);
5853         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5854
5855         if check_revoke_no_close {
5856                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5857                 check_added_monitors!(nodes[0], 1);
5858         }
5859
5860         let mut block = Block {
5861                 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5862                 txdata: vec![],
5863         };
5864         for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5865                 connect_block(&nodes[0], &block, i);
5866                 block.header.prev_blockhash = block.bitcoin_hash();
5867         }
5868         if !check_revoke_no_close {
5869                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5870                 check_closed_broadcast!(nodes[0], false);
5871                 check_added_monitors!(nodes[0], 1);
5872         } else {
5873                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5874         }
5875 }
5876
5877 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5878 // There are only a few cases to test here:
5879 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5880 //    broadcastable commitment transactions result in channel closure,
5881 //  * its included in an unrevoked-but-previous remote commitment transaction,
5882 //  * its included in the latest remote or local commitment transactions.
5883 // We test each of the three possible commitment transactions individually and use both dust and
5884 // non-dust HTLCs.
5885 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5886 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5887 // tested for at least one of the cases in other tests.
5888 #[test]
5889 fn htlc_claim_single_commitment_only_a() {
5890         do_htlc_claim_local_commitment_only(true);
5891         do_htlc_claim_local_commitment_only(false);
5892
5893         do_htlc_claim_current_remote_commitment_only(true);
5894         do_htlc_claim_current_remote_commitment_only(false);
5895 }
5896
5897 #[test]
5898 fn htlc_claim_single_commitment_only_b() {
5899         do_htlc_claim_previous_remote_commitment_only(true, false);
5900         do_htlc_claim_previous_remote_commitment_only(false, false);
5901         do_htlc_claim_previous_remote_commitment_only(true, true);
5902         do_htlc_claim_previous_remote_commitment_only(false, true);
5903 }
5904
5905 fn run_onion_failure_test<F1,F2>(_name: &str, test_case: u8, nodes: &Vec<Node>, route: &Route, payment_hash: &PaymentHash, callback_msg: F1, callback_node: F2, expected_retryable: bool, expected_error_code: Option<u16>, expected_channel_update: Option<HTLCFailChannelUpdate>)
5906         where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
5907                                 F2: FnMut(),
5908 {
5909         run_onion_failure_test_with_fail_intercept(_name, test_case, nodes, route, payment_hash, callback_msg, |_|{}, callback_node, expected_retryable, expected_error_code, expected_channel_update);
5910 }
5911
5912 // test_case
5913 // 0: node1 fails backward
5914 // 1: final node fails backward
5915 // 2: payment completed but the user rejects the payment
5916 // 3: final node fails backward (but tamper onion payloads from node0)
5917 // 100: trigger error in the intermediate node and tamper returning fail_htlc
5918 // 200: trigger error in the final node and tamper returning fail_htlc
5919 fn run_onion_failure_test_with_fail_intercept<F1,F2,F3>(_name: &str, test_case: u8, nodes: &Vec<Node>, route: &Route, payment_hash: &PaymentHash, mut callback_msg: F1, mut callback_fail: F2, mut callback_node: F3, expected_retryable: bool, expected_error_code: Option<u16>, expected_channel_update: Option<HTLCFailChannelUpdate>)
5920         where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
5921                                 F2: for <'a> FnMut(&'a mut msgs::UpdateFailHTLC),
5922                                 F3: FnMut(),
5923 {
5924
5925         // reset block height
5926         let block = Block {
5927                 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5928                 txdata: vec![],
5929         };
5930         for ix in 0..nodes.len() {
5931                 connect_block(&nodes[ix], &block, 1);
5932         }
5933
5934         macro_rules! expect_event {
5935                 ($node: expr, $event_type: path) => {{
5936                         let events = $node.node.get_and_clear_pending_events();
5937                         assert_eq!(events.len(), 1);
5938                         match events[0] {
5939                                 $event_type { .. } => {},
5940                                 _ => panic!("Unexpected event"),
5941                         }
5942                 }}
5943         }
5944
5945         macro_rules! expect_htlc_forward {
5946                 ($node: expr) => {{
5947                         expect_event!($node, Event::PendingHTLCsForwardable);
5948                         $node.node.process_pending_htlc_forwards();
5949                 }}
5950         }
5951
5952         // 0 ~~> 2 send payment
5953         nodes[0].node.send_payment(&route, payment_hash.clone(), &None).unwrap();
5954         check_added_monitors!(nodes[0], 1);
5955         let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5956         // temper update_add (0 => 1)
5957         let mut update_add_0 = update_0.update_add_htlcs[0].clone();
5958         if test_case == 0 || test_case == 3 || test_case == 100 {
5959                 callback_msg(&mut update_add_0);
5960                 callback_node();
5961         }
5962         // 0 => 1 update_add & CS
5963         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_0);
5964         commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
5965
5966         let update_1_0 = match test_case {
5967                 0|100 => { // intermediate node failure; fail backward to 0
5968                         let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5969                         assert!(update_1_0.update_fail_htlcs.len()+update_1_0.update_fail_malformed_htlcs.len()==1 && (update_1_0.update_fail_htlcs.len()==1 || update_1_0.update_fail_malformed_htlcs.len()==1));
5970                         update_1_0
5971                 },
5972                 1|2|3|200 => { // final node failure; forwarding to 2
5973                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5974                         // forwarding on 1
5975                         if test_case != 200 {
5976                                 callback_node();
5977                         }
5978                         expect_htlc_forward!(&nodes[1]);
5979
5980                         let update_1 = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
5981                         check_added_monitors!(&nodes[1], 1);
5982                         assert_eq!(update_1.update_add_htlcs.len(), 1);
5983                         // tamper update_add (1 => 2)
5984                         let mut update_add_1 = update_1.update_add_htlcs[0].clone();
5985                         if test_case != 3 && test_case != 200 {
5986                                 callback_msg(&mut update_add_1);
5987                         }
5988
5989                         // 1 => 2
5990                         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_1);
5991                         commitment_signed_dance!(nodes[2], nodes[1], update_1.commitment_signed, false, true);
5992
5993                         if test_case == 2 || test_case == 200 {
5994                                 expect_htlc_forward!(&nodes[2]);
5995                                 expect_event!(&nodes[2], Event::PaymentReceived);
5996                                 callback_node();
5997                                 expect_pending_htlcs_forwardable!(nodes[2]);
5998                         }
5999
6000                         let update_2_1 = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6001                         if test_case == 2 || test_case == 200 {
6002                                 check_added_monitors!(&nodes[2], 1);
6003                         }
6004                         assert!(update_2_1.update_fail_htlcs.len() == 1);
6005
6006                         let mut fail_msg = update_2_1.update_fail_htlcs[0].clone();
6007                         if test_case == 200 {
6008                                 callback_fail(&mut fail_msg);
6009                         }
6010
6011                         // 2 => 1
6012                         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_msg);
6013                         commitment_signed_dance!(nodes[1], nodes[2], update_2_1.commitment_signed, true);
6014
6015                         // backward fail on 1
6016                         let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6017                         assert!(update_1_0.update_fail_htlcs.len() == 1);
6018                         update_1_0
6019                 },
6020                 _ => unreachable!(),
6021         };
6022
6023         // 1 => 0 commitment_signed_dance
6024         if update_1_0.update_fail_htlcs.len() > 0 {
6025                 let mut fail_msg = update_1_0.update_fail_htlcs[0].clone();
6026                 if test_case == 100 {
6027                         callback_fail(&mut fail_msg);
6028                 }
6029                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6030         } else {
6031                 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_1_0.update_fail_malformed_htlcs[0]);
6032         };
6033
6034         commitment_signed_dance!(nodes[0], nodes[1], update_1_0.commitment_signed, false, true);
6035
6036         let events = nodes[0].node.get_and_clear_pending_events();
6037         assert_eq!(events.len(), 1);
6038         if let &Event::PaymentFailed { payment_hash:_, ref rejected_by_dest, ref error_code, error_data: _ } = &events[0] {
6039                 assert_eq!(*rejected_by_dest, !expected_retryable);
6040                 assert_eq!(*error_code, expected_error_code);
6041         } else {
6042                 panic!("Uexpected event");
6043         }
6044
6045         let events = nodes[0].node.get_and_clear_pending_msg_events();
6046         if expected_channel_update.is_some() {
6047                 assert_eq!(events.len(), 1);
6048                 match events[0] {
6049                         MessageSendEvent::PaymentFailureNetworkUpdate { ref update } => {
6050                                 match update {
6051                                         &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {
6052                                                 if let HTLCFailChannelUpdate::ChannelUpdateMessage { .. } = expected_channel_update.unwrap() {} else {
6053                                                         panic!("channel_update not found!");
6054                                                 }
6055                                         },
6056                                         &HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, ref is_permanent } => {
6057                                                 if let HTLCFailChannelUpdate::ChannelClosed { short_channel_id: ref expected_short_channel_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
6058                                                         assert!(*short_channel_id == *expected_short_channel_id);
6059                                                         assert!(*is_permanent == *expected_is_permanent);
6060                                                 } else {
6061                                                         panic!("Unexpected message event");
6062                                                 }
6063                                         },
6064                                         &HTLCFailChannelUpdate::NodeFailure { ref node_id, ref is_permanent } => {
6065                                                 if let HTLCFailChannelUpdate::NodeFailure { node_id: ref expected_node_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
6066                                                         assert!(*node_id == *expected_node_id);
6067                                                         assert!(*is_permanent == *expected_is_permanent);
6068                                                 } else {
6069                                                         panic!("Unexpected message event");
6070                                                 }
6071                                         },
6072                                 }
6073                         },
6074                         _ => panic!("Unexpected message event"),
6075                 }
6076         } else {
6077                 assert_eq!(events.len(), 0);
6078         }
6079 }
6080
6081 impl msgs::ChannelUpdate {
6082         fn dummy() -> msgs::ChannelUpdate {
6083                 use bitcoin::secp256k1::ffi::Signature as FFISignature;
6084                 use bitcoin::secp256k1::Signature;
6085                 msgs::ChannelUpdate {
6086                         signature: Signature::from(FFISignature::new()),
6087                         contents: msgs::UnsignedChannelUpdate {
6088                                 chain_hash: BlockHash::hash(&vec![0u8][..]),
6089                                 short_channel_id: 0,
6090                                 timestamp: 0,
6091                                 flags: 0,
6092                                 cltv_expiry_delta: 0,
6093                                 htlc_minimum_msat: 0,
6094                                 htlc_maximum_msat: OptionalField::Absent,
6095                                 fee_base_msat: 0,
6096                                 fee_proportional_millionths: 0,
6097                                 excess_data: vec![],
6098                         }
6099                 }
6100         }
6101 }
6102
6103 struct BogusOnionHopData {
6104         data: Vec<u8>
6105 }
6106 impl BogusOnionHopData {
6107         fn new(orig: msgs::OnionHopData) -> Self {
6108                 Self { data: orig.encode() }
6109         }
6110 }
6111 impl Writeable for BogusOnionHopData {
6112         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
6113                 writer.write_all(&self.data[..])
6114         }
6115 }
6116
6117 #[test]
6118 fn test_onion_failure() {
6119         use ln::msgs::ChannelUpdate;
6120         use ln::channelmanager::CLTV_FAR_FAR_AWAY;
6121         use bitcoin::secp256k1;
6122
6123         const BADONION: u16 = 0x8000;
6124         const PERM: u16 = 0x4000;
6125         const NODE: u16 = 0x2000;
6126         const UPDATE: u16 = 0x1000;
6127
6128         let chanmon_cfgs = create_chanmon_cfgs(3);
6129         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6130         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6131         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6132         for node in nodes.iter() {
6133                 *node.keys_manager.override_session_priv.lock().unwrap() = Some(SecretKey::from_slice(&[3; 32]).unwrap());
6134         }
6135         let channels = [create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()), create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known())];
6136         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
6137         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6138         let logger = test_utils::TestLogger::new();
6139         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(), 40000, TEST_FINAL_CLTV, &logger).unwrap();
6140         // positve case
6141         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 40000, 40_000);
6142
6143         // intermediate node failure
6144         run_onion_failure_test("invalid_realm", 0, &nodes, &route, &payment_hash, |msg| {
6145                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
6146                 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
6147                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
6148                 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 40000, &None, cur_height).unwrap();
6149                 let mut new_payloads = Vec::new();
6150                 for payload in onion_payloads.drain(..) {
6151                         new_payloads.push(BogusOnionHopData::new(payload));
6152                 }
6153                 // break the first (non-final) hop payload by swapping the realm (0) byte for a byte
6154                 // describing a length-1 TLV payload, which is obviously bogus.
6155                 new_payloads[0].data[0] = 1;
6156                 msg.onion_routing_packet = onion_utils::construct_onion_packet_bogus_hopdata(new_payloads, onion_keys, [0; 32], &payment_hash);
6157         }, ||{}, true, Some(PERM|22), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));//XXX incremented channels idx here
6158
6159         // final node failure
6160         run_onion_failure_test("invalid_realm", 3, &nodes, &route, &payment_hash, |msg| {
6161                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
6162                 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
6163                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
6164                 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 40000, &None, cur_height).unwrap();
6165                 let mut new_payloads = Vec::new();
6166                 for payload in onion_payloads.drain(..) {
6167                         new_payloads.push(BogusOnionHopData::new(payload));
6168                 }
6169                 // break the last-hop payload by swapping the realm (0) byte for a byte describing a
6170                 // length-1 TLV payload, which is obviously bogus.
6171                 new_payloads[1].data[0] = 1;
6172                 msg.onion_routing_packet = onion_utils::construct_onion_packet_bogus_hopdata(new_payloads, onion_keys, [0; 32], &payment_hash);
6173         }, ||{}, false, Some(PERM|22), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
6174
6175         // the following three with run_onion_failure_test_with_fail_intercept() test only the origin node
6176         // receiving simulated fail messages
6177         // intermediate node failure
6178         run_onion_failure_test_with_fail_intercept("temporary_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
6179                 // trigger error
6180                 msg.amount_msat -= 1;
6181         }, |msg| {
6182                 // and tamper returning error message
6183                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
6184                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
6185                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], NODE|2, &[0;0]);
6186         }, ||{}, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][0].pubkey, is_permanent: false}));
6187
6188         // final node failure
6189         run_onion_failure_test_with_fail_intercept("temporary_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
6190                 // and tamper returning error message
6191                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
6192                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
6193                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], NODE|2, &[0;0]);
6194         }, ||{
6195                 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
6196         }, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][1].pubkey, is_permanent: false}));
6197
6198         // intermediate node failure
6199         run_onion_failure_test_with_fail_intercept("permanent_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
6200                 msg.amount_msat -= 1;
6201         }, |msg| {
6202                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
6203                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
6204                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|2, &[0;0]);
6205         }, ||{}, true, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][0].pubkey, is_permanent: true}));
6206
6207         // final node failure
6208         run_onion_failure_test_with_fail_intercept("permanent_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
6209                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
6210                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
6211                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|2, &[0;0]);
6212         }, ||{
6213                 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
6214         }, false, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][1].pubkey, is_permanent: true}));
6215
6216         // intermediate node failure
6217         run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
6218                 msg.amount_msat -= 1;
6219         }, |msg| {
6220                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
6221                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
6222                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|3, &[0;0]);
6223         }, ||{
6224                 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
6225         }, true, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][0].pubkey, is_permanent: true}));
6226
6227         // final node failure
6228         run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
6229                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
6230                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
6231                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|3, &[0;0]);
6232         }, ||{
6233                 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
6234         }, false, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][1].pubkey, is_permanent: true}));
6235
6236         run_onion_failure_test("invalid_onion_version", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.version = 1; }, ||{}, true,
6237                 Some(BADONION|PERM|4), None);
6238
6239         run_onion_failure_test("invalid_onion_hmac", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.hmac = [3; 32]; }, ||{}, true,
6240                 Some(BADONION|PERM|5), None);
6241
6242         run_onion_failure_test("invalid_onion_key", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.public_key = Err(secp256k1::Error::InvalidPublicKey);}, ||{}, true,
6243                 Some(BADONION|PERM|6), None);
6244
6245         run_onion_failure_test_with_fail_intercept("temporary_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
6246                 msg.amount_msat -= 1;
6247         }, |msg| {
6248                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
6249                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
6250                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], UPDATE|7, &ChannelUpdate::dummy().encode_with_len()[..]);
6251         }, ||{}, true, Some(UPDATE|7), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
6252
6253         run_onion_failure_test_with_fail_intercept("permanent_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
6254                 msg.amount_msat -= 1;
6255         }, |msg| {
6256                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
6257                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
6258                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|8, &[0;0]);
6259                 // short_channel_id from the processing node
6260         }, ||{}, true, Some(PERM|8), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
6261
6262         run_onion_failure_test_with_fail_intercept("required_channel_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
6263                 msg.amount_msat -= 1;
6264         }, |msg| {
6265                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
6266                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
6267                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|9, &[0;0]);
6268                 // short_channel_id from the processing node
6269         }, ||{}, true, Some(PERM|9), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
6270
6271         let mut bogus_route = route.clone();
6272         bogus_route.paths[0][1].short_channel_id -= 1;
6273         run_onion_failure_test("unknown_next_peer", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(PERM|10),
6274           Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: bogus_route.paths[0][1].short_channel_id, is_permanent:true}));
6275
6276         let amt_to_forward = nodes[1].node.channel_state.lock().unwrap().by_id.get(&channels[1].2).unwrap().get_their_htlc_minimum_msat() - 1;
6277         let mut bogus_route = route.clone();
6278         let route_len = bogus_route.paths[0].len();
6279         bogus_route.paths[0][route_len-1].fee_msat = amt_to_forward;
6280         run_onion_failure_test("amount_below_minimum", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(UPDATE|11), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
6281
6282         //TODO: with new config API, we will be able to generate both valid and
6283         //invalid channel_update cases.
6284         run_onion_failure_test("fee_insufficient", 0, &nodes, &route, &payment_hash, |msg| {
6285                 msg.amount_msat -= 1;
6286         }, || {}, true, Some(UPDATE|12), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
6287
6288         run_onion_failure_test("incorrect_cltv_expiry", 0, &nodes, &route, &payment_hash, |msg| {
6289                 // need to violate: cltv_expiry - cltv_expiry_delta >= outgoing_cltv_value
6290                 msg.cltv_expiry -= 1;
6291         }, || {}, true, Some(UPDATE|13), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
6292
6293         run_onion_failure_test("expiry_too_soon", 0, &nodes, &route, &payment_hash, |msg| {
6294                 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
6295                 let block = Block {
6296                         header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
6297                         txdata: vec![],
6298                 };
6299
6300                 connect_block(&nodes[1], &block, height);
6301         }, ||{}, true, Some(UPDATE|14), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
6302
6303         run_onion_failure_test("unknown_payment_hash", 2, &nodes, &route, &payment_hash, |_| {}, || {
6304                 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
6305         }, false, Some(PERM|15), None);
6306
6307         run_onion_failure_test("final_expiry_too_soon", 1, &nodes, &route, &payment_hash, |msg| {
6308                 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
6309                 let block = Block {
6310                         header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
6311                         txdata: vec![],
6312                 };
6313
6314                 connect_block(&nodes[2], &block, height);
6315         }, || {}, true, Some(17), None);
6316
6317         run_onion_failure_test("final_incorrect_cltv_expiry", 1, &nodes, &route, &payment_hash, |_| {}, || {
6318                 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().forward_htlcs.iter_mut() {
6319                         for f in pending_forwards.iter_mut() {
6320                                 match f {
6321                                         &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
6322                                                 forward_info.outgoing_cltv_value += 1,
6323                                         _ => {},
6324                                 }
6325                         }
6326                 }
6327         }, true, Some(18), None);
6328
6329         run_onion_failure_test("final_incorrect_htlc_amount", 1, &nodes, &route, &payment_hash, |_| {}, || {
6330                 // violate amt_to_forward > msg.amount_msat
6331                 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().forward_htlcs.iter_mut() {
6332                         for f in pending_forwards.iter_mut() {
6333                                 match f {
6334                                         &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
6335                                                 forward_info.amt_to_forward -= 1,
6336                                         _ => {},
6337                                 }
6338                         }
6339                 }
6340         }, true, Some(19), None);
6341
6342         run_onion_failure_test("channel_disabled", 0, &nodes, &route, &payment_hash, |_| {}, || {
6343                 // disconnect event to the channel between nodes[1] ~ nodes[2]
6344                 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
6345                 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6346         }, true, Some(UPDATE|20), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
6347         reconnect_nodes(&nodes[1], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
6348
6349         run_onion_failure_test("expiry_too_far", 0, &nodes, &route, &payment_hash, |msg| {
6350                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
6351                 let mut route = route.clone();
6352                 let height = 1;
6353                 route.paths[0][1].cltv_expiry_delta += CLTV_FAR_FAR_AWAY + route.paths[0][0].cltv_expiry_delta + 1;
6354                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
6355                 let (onion_payloads, _, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 40000, &None, height).unwrap();
6356                 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
6357                 msg.cltv_expiry = htlc_cltv;
6358                 msg.onion_routing_packet = onion_packet;
6359         }, ||{}, true, Some(21), None);
6360 }
6361
6362 #[test]
6363 #[should_panic]
6364 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
6365         let chanmon_cfgs = create_chanmon_cfgs(2);
6366         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6367         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6368         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6369         //Force duplicate channel ids
6370         for node in nodes.iter() {
6371                 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
6372         }
6373
6374         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
6375         let channel_value_satoshis=10000;
6376         let push_msat=10001;
6377         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6378         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6379         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6380
6381         //Create a second channel with a channel_id collision
6382         assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6383 }
6384
6385 #[test]
6386 fn bolt2_open_channel_sending_node_checks_part2() {
6387         let chanmon_cfgs = create_chanmon_cfgs(2);
6388         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6389         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6390         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6391
6392         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
6393         let channel_value_satoshis=2^24;
6394         let push_msat=10001;
6395         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6396
6397         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
6398         let channel_value_satoshis=10000;
6399         // Test when push_msat is equal to 1000 * funding_satoshis.
6400         let push_msat=1000*channel_value_satoshis+1;
6401         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6402
6403         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
6404         let channel_value_satoshis=10000;
6405         let push_msat=10001;
6406         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
6407         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6408         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
6409
6410         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
6411         // 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
6412         assert!(node0_to_1_send_open_channel.channel_flags<=1);
6413
6414         // 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.
6415         assert!(BREAKDOWN_TIMEOUT>0);
6416         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
6417
6418         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
6419         let chain_hash=genesis_block(Network::Testnet).header.bitcoin_hash();
6420         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
6421
6422         // 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.
6423         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
6424         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
6425         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
6426         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
6427         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6428 }
6429
6430 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6431 // 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.
6432 //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.
6433
6434 #[test]
6435 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6436         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6437         let chanmon_cfgs = create_chanmon_cfgs(2);
6438         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6439         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6440         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6441         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6442
6443         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6444         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6445         let logger = test_utils::TestLogger::new();
6446         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();
6447         route.paths[0][0].fee_msat = 100;
6448
6449         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6450                 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6451         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6452         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6453 }
6454
6455 #[test]
6456 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6457         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6458         let chanmon_cfgs = create_chanmon_cfgs(2);
6459         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6460         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6461         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6462         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6463         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6464
6465         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6466         let logger = test_utils::TestLogger::new();
6467         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();
6468         route.paths[0][0].fee_msat = 0;
6469         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6470                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6471
6472         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6473         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6474 }
6475
6476 #[test]
6477 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6478         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6479         let chanmon_cfgs = create_chanmon_cfgs(2);
6480         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6481         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6482         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6483         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6484
6485         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6486         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6487         let logger = test_utils::TestLogger::new();
6488         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();
6489         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6490         check_added_monitors!(nodes[0], 1);
6491         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6492         updates.update_add_htlcs[0].amount_msat = 0;
6493
6494         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6495         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6496         check_closed_broadcast!(nodes[1], true).unwrap();
6497         check_added_monitors!(nodes[1], 1);
6498 }
6499
6500 #[test]
6501 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6502         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6503         //It is enforced when constructing a route.
6504         let chanmon_cfgs = create_chanmon_cfgs(2);
6505         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6506         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6507         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6508         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 0, InitFeatures::known(), InitFeatures::known());
6509         let logger = test_utils::TestLogger::new();
6510
6511         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6512
6513         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6514         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &[], 100000000, 500000001, &logger).unwrap();
6515         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::RouteError { ref err },
6516                 assert_eq!(err, &"Channel CLTV overflowed?"));
6517 }
6518
6519 #[test]
6520 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6521         //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.
6522         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6523         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6524         let chanmon_cfgs = create_chanmon_cfgs(2);
6525         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6526         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6527         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6528         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6529         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().their_max_accepted_htlcs as u64;
6530
6531         let logger = test_utils::TestLogger::new();
6532         for i in 0..max_accepted_htlcs {
6533                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6534                 let payment_event = {
6535                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6536                         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();
6537                         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6538                         check_added_monitors!(nodes[0], 1);
6539
6540                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6541                         assert_eq!(events.len(), 1);
6542                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6543                                 assert_eq!(htlcs[0].htlc_id, i);
6544                         } else {
6545                                 assert!(false);
6546                         }
6547                         SendEvent::from_event(events.remove(0))
6548                 };
6549                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6550                 check_added_monitors!(nodes[1], 0);
6551                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6552
6553                 expect_pending_htlcs_forwardable!(nodes[1]);
6554                 expect_payment_received!(nodes[1], our_payment_hash, 100000);
6555         }
6556         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6557         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6558         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();
6559         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6560                 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6561
6562         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6563         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6564 }
6565
6566 #[test]
6567 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6568         //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.
6569         let chanmon_cfgs = create_chanmon_cfgs(2);
6570         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6571         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6572         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6573         let channel_value = 100000;
6574         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6575         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).their_max_htlc_value_in_flight_msat;
6576
6577         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight, max_in_flight);
6578
6579         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6580         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6581         let logger = test_utils::TestLogger::new();
6582         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();
6583         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6584                 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)));
6585
6586         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6587         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);
6588
6589         send_payment(&nodes[0], &[&nodes[1]], max_in_flight, max_in_flight);
6590 }
6591
6592 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6593 #[test]
6594 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6595         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6596         let chanmon_cfgs = create_chanmon_cfgs(2);
6597         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6598         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6599         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6600         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6601         let htlc_minimum_msat: u64;
6602         {
6603                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6604                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6605                 htlc_minimum_msat = channel.get_our_htlc_minimum_msat();
6606         }
6607
6608         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6609         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6610         let logger = test_utils::TestLogger::new();
6611         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &[], htlc_minimum_msat, TEST_FINAL_CLTV, &logger).unwrap();
6612         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6613         check_added_monitors!(nodes[0], 1);
6614         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6615         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6616         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6617         assert!(nodes[1].node.list_channels().is_empty());
6618         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6619         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()));
6620         check_added_monitors!(nodes[1], 1);
6621 }
6622
6623 #[test]
6624 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6625         //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
6626         let chanmon_cfgs = create_chanmon_cfgs(2);
6627         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6628         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6629         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6630         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6631         let logger = test_utils::TestLogger::new();
6632
6633         let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6634         let channel_reserve = chan_stat.channel_reserve_msat;
6635         let feerate = get_feerate!(nodes[0], chan.2);
6636         // The 2* and +1 are for the fee spike reserve.
6637         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1);
6638
6639         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
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, &[], max_can_send, 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
6647         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6648         // at this time channel-initiatee receivers are not required to enforce that senders
6649         // respect the fee_spike_reserve.
6650         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6651         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6652
6653         assert!(nodes[1].node.list_channels().is_empty());
6654         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6655         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6656         check_added_monitors!(nodes[1], 1);
6657 }
6658
6659 #[test]
6660 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6661         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6662         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6663         let chanmon_cfgs = create_chanmon_cfgs(2);
6664         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6665         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6666         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6667         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6668         let logger = test_utils::TestLogger::new();
6669
6670         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6671         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6672
6673         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6674         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();
6675
6676         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
6677         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6678         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &None, cur_height).unwrap();
6679         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6680
6681         let mut msg = msgs::UpdateAddHTLC {
6682                 channel_id: chan.2,
6683                 htlc_id: 0,
6684                 amount_msat: 1000,
6685                 payment_hash: our_payment_hash,
6686                 cltv_expiry: htlc_cltv,
6687                 onion_routing_packet: onion_packet.clone(),
6688         };
6689
6690         for i in 0..super::channel::OUR_MAX_HTLCS {
6691                 msg.htlc_id = i as u64;
6692                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6693         }
6694         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6695         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6696
6697         assert!(nodes[1].node.list_channels().is_empty());
6698         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6699         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6700         check_added_monitors!(nodes[1], 1);
6701 }
6702
6703 #[test]
6704 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6705         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6706         let chanmon_cfgs = create_chanmon_cfgs(2);
6707         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6708         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6709         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6710         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6711         let logger = test_utils::TestLogger::new();
6712
6713         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6714         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6715         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();
6716         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6717         check_added_monitors!(nodes[0], 1);
6718         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6719         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).their_max_htlc_value_in_flight_msat + 1;
6720         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6721
6722         assert!(nodes[1].node.list_channels().is_empty());
6723         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6724         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6725         check_added_monitors!(nodes[1], 1);
6726 }
6727
6728 #[test]
6729 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6730         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6731         let chanmon_cfgs = create_chanmon_cfgs(2);
6732         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6733         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6734         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6735         let logger = test_utils::TestLogger::new();
6736
6737         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6738         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6739         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6740         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();
6741         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6742         check_added_monitors!(nodes[0], 1);
6743         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6744         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6745         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6746
6747         assert!(nodes[1].node.list_channels().is_empty());
6748         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6749         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6750         check_added_monitors!(nodes[1], 1);
6751 }
6752
6753 #[test]
6754 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6755         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6756         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6757         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6758         let chanmon_cfgs = create_chanmon_cfgs(2);
6759         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6760         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6761         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6762         let logger = test_utils::TestLogger::new();
6763
6764         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6765         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6766         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6767         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();
6768         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6769         check_added_monitors!(nodes[0], 1);
6770         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6771         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6772
6773         //Disconnect and Reconnect
6774         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6775         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6776         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6777         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6778         assert_eq!(reestablish_1.len(), 1);
6779         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6780         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6781         assert_eq!(reestablish_2.len(), 1);
6782         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6783         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6784         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6785         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6786
6787         //Resend HTLC
6788         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6789         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6790         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6791         check_added_monitors!(nodes[1], 1);
6792         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6793
6794         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6795
6796         assert!(nodes[1].node.list_channels().is_empty());
6797         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6798         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6799         check_added_monitors!(nodes[1], 1);
6800 }
6801
6802 #[test]
6803 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6804         //BOLT 2 Requirement: until the corresponding HTLC is irrevocably committed in both sides' commitment transactions:     MUST NOT send an update_fulfill_htlc, update_fail_htlc, or update_fail_malformed_htlc.
6805
6806         let chanmon_cfgs = create_chanmon_cfgs(2);
6807         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6808         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6809         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6810         let logger = test_utils::TestLogger::new();
6811         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6812         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6813         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6814         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();
6815         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6816
6817         check_added_monitors!(nodes[0], 1);
6818         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6819         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6820
6821         let update_msg = msgs::UpdateFulfillHTLC{
6822                 channel_id: chan.2,
6823                 htlc_id: 0,
6824                 payment_preimage: our_payment_preimage,
6825         };
6826
6827         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6828
6829         assert!(nodes[0].node.list_channels().is_empty());
6830         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6831         assert!(regex::Regex::new(r"Remote tried to fulfill/fail HTLC \(\d+\) before it had been committed").unwrap().is_match(err_msg.data.as_str()));
6832         check_added_monitors!(nodes[0], 1);
6833 }
6834
6835 #[test]
6836 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6837         //BOLT 2 Requirement: until the corresponding HTLC is irrevocably committed in both sides' commitment transactions:     MUST NOT send an update_fulfill_htlc, update_fail_htlc, or update_fail_malformed_htlc.
6838
6839         let chanmon_cfgs = create_chanmon_cfgs(2);
6840         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6841         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6842         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6843         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6844         let logger = test_utils::TestLogger::new();
6845
6846         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6847         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6848         let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6849         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6850         check_added_monitors!(nodes[0], 1);
6851         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6852         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6853
6854         let update_msg = msgs::UpdateFailHTLC{
6855                 channel_id: chan.2,
6856                 htlc_id: 0,
6857                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6858         };
6859
6860         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6861
6862         assert!(nodes[0].node.list_channels().is_empty());
6863         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6864         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()));
6865         check_added_monitors!(nodes[0], 1);
6866 }
6867
6868 #[test]
6869 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6870         //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.
6871
6872         let chanmon_cfgs = create_chanmon_cfgs(2);
6873         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6874         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6875         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6876         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6877         let logger = test_utils::TestLogger::new();
6878
6879         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6880         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6881         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();
6882         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6883         check_added_monitors!(nodes[0], 1);
6884         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6885         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6886
6887         let update_msg = msgs::UpdateFailMalformedHTLC{
6888                 channel_id: chan.2,
6889                 htlc_id: 0,
6890                 sha256_of_onion: [1; 32],
6891                 failure_code: 0x8000,
6892         };
6893
6894         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6895
6896         assert!(nodes[0].node.list_channels().is_empty());
6897         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6898         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()));
6899         check_added_monitors!(nodes[0], 1);
6900 }
6901
6902 #[test]
6903 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6904         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6905
6906         let chanmon_cfgs = create_chanmon_cfgs(2);
6907         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6908         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6909         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6910         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6911
6912         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6913
6914         nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6915         check_added_monitors!(nodes[1], 1);
6916
6917         let events = nodes[1].node.get_and_clear_pending_msg_events();
6918         assert_eq!(events.len(), 1);
6919         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6920                 match events[0] {
6921                         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, .. } } => {
6922                                 assert!(update_add_htlcs.is_empty());
6923                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6924                                 assert!(update_fail_htlcs.is_empty());
6925                                 assert!(update_fail_malformed_htlcs.is_empty());
6926                                 assert!(update_fee.is_none());
6927                                 update_fulfill_htlcs[0].clone()
6928                         },
6929                         _ => panic!("Unexpected event"),
6930                 }
6931         };
6932
6933         update_fulfill_msg.htlc_id = 1;
6934
6935         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6936
6937         assert!(nodes[0].node.list_channels().is_empty());
6938         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6939         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6940         check_added_monitors!(nodes[0], 1);
6941 }
6942
6943 #[test]
6944 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6945         //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.
6946
6947         let chanmon_cfgs = create_chanmon_cfgs(2);
6948         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6949         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6950         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6951         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6952
6953         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6954
6955         nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6956         check_added_monitors!(nodes[1], 1);
6957
6958         let events = nodes[1].node.get_and_clear_pending_msg_events();
6959         assert_eq!(events.len(), 1);
6960         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6961                 match events[0] {
6962                         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, .. } } => {
6963                                 assert!(update_add_htlcs.is_empty());
6964                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6965                                 assert!(update_fail_htlcs.is_empty());
6966                                 assert!(update_fail_malformed_htlcs.is_empty());
6967                                 assert!(update_fee.is_none());
6968                                 update_fulfill_htlcs[0].clone()
6969                         },
6970                         _ => panic!("Unexpected event"),
6971                 }
6972         };
6973
6974         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6975
6976         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6977
6978         assert!(nodes[0].node.list_channels().is_empty());
6979         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6980         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6981         check_added_monitors!(nodes[0], 1);
6982 }
6983
6984 #[test]
6985 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6986         //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.
6987
6988         let chanmon_cfgs = create_chanmon_cfgs(2);
6989         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6990         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6991         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6992         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6993         let logger = test_utils::TestLogger::new();
6994
6995         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6996         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6997         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();
6998         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6999         check_added_monitors!(nodes[0], 1);
7000
7001         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7002         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7003
7004         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
7005         check_added_monitors!(nodes[1], 0);
7006         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
7007
7008         let events = nodes[1].node.get_and_clear_pending_msg_events();
7009
7010         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
7011                 match events[0] {
7012                         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, .. } } => {
7013                                 assert!(update_add_htlcs.is_empty());
7014                                 assert!(update_fulfill_htlcs.is_empty());
7015                                 assert!(update_fail_htlcs.is_empty());
7016                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7017                                 assert!(update_fee.is_none());
7018                                 update_fail_malformed_htlcs[0].clone()
7019                         },
7020                         _ => panic!("Unexpected event"),
7021                 }
7022         };
7023         update_msg.failure_code &= !0x8000;
7024         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
7025
7026         assert!(nodes[0].node.list_channels().is_empty());
7027         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7028         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
7029         check_added_monitors!(nodes[0], 1);
7030 }
7031
7032 #[test]
7033 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
7034         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
7035         //    * 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.
7036
7037         let chanmon_cfgs = create_chanmon_cfgs(3);
7038         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7039         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7040         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7041         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7042         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7043         let logger = test_utils::TestLogger::new();
7044
7045         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
7046
7047         //First hop
7048         let mut payment_event = {
7049                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
7050                 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();
7051                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
7052                 check_added_monitors!(nodes[0], 1);
7053                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7054                 assert_eq!(events.len(), 1);
7055                 SendEvent::from_event(events.remove(0))
7056         };
7057         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7058         check_added_monitors!(nodes[1], 0);
7059         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7060         expect_pending_htlcs_forwardable!(nodes[1]);
7061         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7062         assert_eq!(events_2.len(), 1);
7063         check_added_monitors!(nodes[1], 1);
7064         payment_event = SendEvent::from_event(events_2.remove(0));
7065         assert_eq!(payment_event.msgs.len(), 1);
7066
7067         //Second Hop
7068         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7069         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7070         check_added_monitors!(nodes[2], 0);
7071         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7072
7073         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7074         assert_eq!(events_3.len(), 1);
7075         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
7076                 match events_3[0] {
7077                         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 } } => {
7078                                 assert!(update_add_htlcs.is_empty());
7079                                 assert!(update_fulfill_htlcs.is_empty());
7080                                 assert!(update_fail_htlcs.is_empty());
7081                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7082                                 assert!(update_fee.is_none());
7083                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
7084                         },
7085                         _ => panic!("Unexpected event"),
7086                 }
7087         };
7088
7089         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
7090
7091         check_added_monitors!(nodes[1], 0);
7092         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
7093         expect_pending_htlcs_forwardable!(nodes[1]);
7094         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7095         assert_eq!(events_4.len(), 1);
7096
7097         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7098         match events_4[0] {
7099                 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, .. } } => {
7100                         assert!(update_add_htlcs.is_empty());
7101                         assert!(update_fulfill_htlcs.is_empty());
7102                         assert_eq!(update_fail_htlcs.len(), 1);
7103                         assert!(update_fail_malformed_htlcs.is_empty());
7104                         assert!(update_fee.is_none());
7105                 },
7106                 _ => panic!("Unexpected event"),
7107         };
7108
7109         check_added_monitors!(nodes[1], 1);
7110 }
7111
7112 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7113         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7114         // 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
7115         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7116
7117         let chanmon_cfgs = create_chanmon_cfgs(2);
7118         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7119         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7120         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7121         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7122
7123         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
7124
7125         // We route 2 dust-HTLCs between A and B
7126         let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7127         let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7128         route_payment(&nodes[0], &[&nodes[1]], 1000000);
7129
7130         // Cache one local commitment tx as previous
7131         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7132
7133         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7134         assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2, &None));
7135         check_added_monitors!(nodes[1], 0);
7136         expect_pending_htlcs_forwardable!(nodes[1]);
7137         check_added_monitors!(nodes[1], 1);
7138
7139         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7140         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7141         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7142         check_added_monitors!(nodes[0], 1);
7143
7144         // Cache one local commitment tx as lastest
7145         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7146
7147         let events = nodes[0].node.get_and_clear_pending_msg_events();
7148         match events[0] {
7149                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7150                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7151                 },
7152                 _ => panic!("Unexpected event"),
7153         }
7154         match events[1] {
7155                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7156                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7157                 },
7158                 _ => panic!("Unexpected event"),
7159         }
7160
7161         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7162         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7163         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7164
7165         if announce_latest {
7166                 connect_block(&nodes[0], &Block { header, txdata: vec![as_last_commitment_tx[0].clone()]}, 1);
7167         } else {
7168                 connect_block(&nodes[0], &Block { header, txdata: vec![as_prev_commitment_tx[0].clone()]}, 1);
7169         }
7170
7171         check_closed_broadcast!(nodes[0], false);
7172         check_added_monitors!(nodes[0], 1);
7173
7174         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7175         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 1, true,  header.bitcoin_hash());
7176         let events = nodes[0].node.get_and_clear_pending_events();
7177         // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
7178         assert_eq!(events.len(), 2);
7179         let mut first_failed = false;
7180         for event in events {
7181                 match event {
7182                         Event::PaymentFailed { payment_hash, .. } => {
7183                                 if payment_hash == payment_hash_1 {
7184                                         assert!(!first_failed);
7185                                         first_failed = true;
7186                                 } else {
7187                                         assert_eq!(payment_hash, payment_hash_2);
7188                                 }
7189                         }
7190                         _ => panic!("Unexpected event"),
7191                 }
7192         }
7193 }
7194
7195 #[test]
7196 fn test_failure_delay_dust_htlc_local_commitment() {
7197         do_test_failure_delay_dust_htlc_local_commitment(true);
7198         do_test_failure_delay_dust_htlc_local_commitment(false);
7199 }
7200
7201 #[test]
7202 fn test_no_failure_dust_htlc_local_commitment() {
7203         // Transaction filters for failing back dust htlc based on local commitment txn infos has been
7204         // prone to error, we test here that a dummy transaction don't fail them.
7205
7206         let chanmon_cfgs = create_chanmon_cfgs(2);
7207         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7208         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7209         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7210         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7211
7212         // Rebalance a bit
7213         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7214
7215         let as_dust_limit = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
7216         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
7217
7218         // We route 2 dust-HTLCs between A and B
7219         let (preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7220         let (preimage_2, _) = route_payment(&nodes[1], &[&nodes[0]], as_dust_limit*1000);
7221
7222         // Build a dummy invalid transaction trying to spend a commitment tx
7223         let input = TxIn {
7224                 previous_output: BitcoinOutPoint { txid: chan.3.txid(), vout: 0 },
7225                 script_sig: Script::new(),
7226                 sequence: 0,
7227                 witness: Vec::new(),
7228         };
7229
7230         let outp = TxOut {
7231                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
7232                 value: 10000,
7233         };
7234
7235         let dummy_tx = Transaction {
7236                 version: 2,
7237                 lock_time: 0,
7238                 input: vec![input],
7239                 output: vec![outp]
7240         };
7241
7242         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7243         nodes[0].chain_monitor.chain_monitor.block_connected(&header, &[(0, &dummy_tx)], 1);
7244         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7245         assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
7246         // We broadcast a few more block to check everything is all right
7247         connect_blocks(&nodes[0], 20, 1, true, header.bitcoin_hash());
7248         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7249         assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
7250
7251         claim_payment(&nodes[0], &vec!(&nodes[1])[..], preimage_1, bs_dust_limit*1000);
7252         claim_payment(&nodes[1], &vec!(&nodes[0])[..], preimage_2, as_dust_limit*1000);
7253 }
7254
7255 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7256         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7257         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7258         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7259         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7260         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7261         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7262
7263         let chanmon_cfgs = create_chanmon_cfgs(3);
7264         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7265         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7266         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7267         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7268
7269         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
7270
7271         let (_payment_preimage_1, dust_hash) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7272         let (_payment_preimage_2, non_dust_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7273
7274         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7275         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7276
7277         // We revoked bs_commitment_tx
7278         if revoked {
7279                 let (payment_preimage_3, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7280                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 1_000_000);
7281         }
7282
7283         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7284         let mut timeout_tx = Vec::new();
7285         if local {
7286                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7287                 connect_block(&nodes[0], &Block { header, txdata: vec![as_commitment_tx[0].clone()]}, 1);
7288                 check_closed_broadcast!(nodes[0], false);
7289                 check_added_monitors!(nodes[0], 1);
7290                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7291                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7292                 let parent_hash  = connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 2, true, header.bitcoin_hash());
7293                 expect_payment_failed!(nodes[0], dust_hash, true);
7294                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7295                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7296                 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7297                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7298                 connect_block(&nodes[0], &Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
7299                 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7300                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 8, true, header_3.bitcoin_hash());
7301                 expect_payment_failed!(nodes[0], non_dust_hash, true);
7302         } else {
7303                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7304                 connect_block(&nodes[0], &Block { header, txdata: vec![bs_commitment_tx[0].clone()]}, 1);
7305                 check_closed_broadcast!(nodes[0], false);
7306                 check_added_monitors!(nodes[0], 1);
7307                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7308                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7309                 let parent_hash  = connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 2, true, header.bitcoin_hash());
7310                 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7311                 if !revoked {
7312                         expect_payment_failed!(nodes[0], dust_hash, true);
7313                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7314                         // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7315                         connect_block(&nodes[0], &Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
7316                         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7317                         let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7318                         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 8, true, header_3.bitcoin_hash());
7319                         expect_payment_failed!(nodes[0], non_dust_hash, true);
7320                 } else {
7321                         // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7322                         // commitment tx
7323                         let events = nodes[0].node.get_and_clear_pending_events();
7324                         assert_eq!(events.len(), 2);
7325                         let first;
7326                         match events[0] {
7327                                 Event::PaymentFailed { payment_hash, .. } => {
7328                                         if payment_hash == dust_hash { first = true; }
7329                                         else { first = false; }
7330                                 },
7331                                 _ => panic!("Unexpected event"),
7332                         }
7333                         match events[1] {
7334                                 Event::PaymentFailed { payment_hash, .. } => {
7335                                         if first { assert_eq!(payment_hash, non_dust_hash); }
7336                                         else { assert_eq!(payment_hash, dust_hash); }
7337                                 },
7338                                 _ => panic!("Unexpected event"),
7339                         }
7340                 }
7341         }
7342 }
7343
7344 #[test]
7345 fn test_sweep_outbound_htlc_failure_update() {
7346         do_test_sweep_outbound_htlc_failure_update(false, true);
7347         do_test_sweep_outbound_htlc_failure_update(false, false);
7348         do_test_sweep_outbound_htlc_failure_update(true, false);
7349 }
7350
7351 #[test]
7352 fn test_upfront_shutdown_script() {
7353         // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
7354         // enforce it at shutdown message
7355
7356         let mut config = UserConfig::default();
7357         config.channel_options.announced_channel = true;
7358         config.peer_channel_config_limits.force_announced_channel_preference = false;
7359         config.channel_options.commit_upfront_shutdown_pubkey = false;
7360         let user_cfgs = [None, Some(config), None];
7361         let chanmon_cfgs = create_chanmon_cfgs(3);
7362         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7363         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7364         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7365
7366         // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
7367         let flags = InitFeatures::known();
7368         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7369         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7370         let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7371         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7372         // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that  we disconnect peer
7373         nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
7374     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()));
7375         check_added_monitors!(nodes[2], 1);
7376
7377         // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
7378         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7379         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7380         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7381         // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
7382         nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
7383         let events = nodes[2].node.get_and_clear_pending_msg_events();
7384         assert_eq!(events.len(), 1);
7385         match events[0] {
7386                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7387                 _ => panic!("Unexpected event"),
7388         }
7389
7390         // We test that if case of peer non-signaling we don't enforce committed script at channel opening
7391         let flags_no = InitFeatures::known().clear_upfront_shutdown_script();
7392         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone());
7393         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7394         let mut node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
7395         node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7396         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_1_shutdown);
7397         let events = nodes[1].node.get_and_clear_pending_msg_events();
7398         assert_eq!(events.len(), 1);
7399         match events[0] {
7400                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7401                 _ => panic!("Unexpected event"),
7402         }
7403
7404         // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7405         // channel smoothly, opt-out is from channel initiator here
7406         let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone());
7407         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7408         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7409         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7410         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
7411         let events = nodes[0].node.get_and_clear_pending_msg_events();
7412         assert_eq!(events.len(), 1);
7413         match events[0] {
7414                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7415                 _ => panic!("Unexpected event"),
7416         }
7417
7418         //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7419         //// channel smoothly
7420         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone());
7421         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7422         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7423         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7424         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
7425         let events = nodes[0].node.get_and_clear_pending_msg_events();
7426         assert_eq!(events.len(), 2);
7427         match events[0] {
7428                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7429                 _ => panic!("Unexpected event"),
7430         }
7431         match events[1] {
7432                 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7433                 _ => panic!("Unexpected event"),
7434         }
7435 }
7436
7437 #[test]
7438 fn test_user_configurable_csv_delay() {
7439         // We test our channel constructors yield errors when we pass them absurd csv delay
7440
7441         let mut low_our_to_self_config = UserConfig::default();
7442         low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7443         let mut high_their_to_self_config = UserConfig::default();
7444         high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7445         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7446         let chanmon_cfgs = create_chanmon_cfgs(2);
7447         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7448         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7449         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7450
7451         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7452         let keys_manager: Arc<KeysInterface<ChanKeySigner = EnforcingChannelKeys>> = Arc::new(test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet));
7453         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) {
7454                 match error {
7455                         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())); },
7456                         _ => panic!("Unexpected event"),
7457                 }
7458         } else { assert!(false) }
7459
7460         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7461         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7462         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7463         open_channel.to_self_delay = 200;
7464         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) {
7465                 match error {
7466                         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()));  },
7467                         _ => panic!("Unexpected event"),
7468                 }
7469         } else { assert!(false); }
7470
7471         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7472         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7473         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()));
7474         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7475         accept_channel.to_self_delay = 200;
7476         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7477         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7478                 match action {
7479                         &ErrorAction::SendErrorMessage { ref msg } => {
7480                                 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()));
7481                         },
7482                         _ => { assert!(false); }
7483                 }
7484         } else { assert!(false); }
7485
7486         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7487         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7488         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7489         open_channel.to_self_delay = 200;
7490         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) {
7491                 match error {
7492                         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())); },
7493                         _ => panic!("Unexpected event"),
7494                 }
7495         } else { assert!(false); }
7496 }
7497
7498 #[test]
7499 fn test_data_loss_protect() {
7500         // We want to be sure that :
7501         // * we don't broadcast our Local Commitment Tx in case of fallen behind
7502         // * we close channel in case of detecting other being fallen behind
7503         // * we are able to claim our own outputs thanks to to_remote being static
7504         let keys_manager;
7505         let logger;
7506         let fee_estimator;
7507         let tx_broadcaster;
7508         let chain_source;
7509         let monitor;
7510         let node_state_0;
7511         let chanmon_cfgs = create_chanmon_cfgs(2);
7512         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7513         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7514         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7515
7516         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7517
7518         // Cache node A state before any channel update
7519         let previous_node_state = nodes[0].node.encode();
7520         let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7521         nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut previous_chain_monitor_state).unwrap();
7522
7523         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7524         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7525
7526         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7527         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7528
7529         // Restore node A from previous state
7530         logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7531         let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut ::std::io::Cursor::new(previous_chain_monitor_state.0)).unwrap().1;
7532         chain_source = test_utils::TestChainSource::new(Network::Testnet);
7533         tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
7534         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
7535         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
7536         monitor = test_utils::TestChainMonitor::new(&tx_broadcaster, &logger, &fee_estimator);
7537         node_state_0 = {
7538                 let mut channel_monitors = HashMap::new();
7539                 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7540                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut ::std::io::Cursor::new(previous_node_state), ChannelManagerReadArgs {
7541                         keys_manager: &keys_manager,
7542                         fee_estimator: &fee_estimator,
7543                         chain_monitor: &monitor,
7544                         logger: &logger,
7545                         tx_broadcaster: &tx_broadcaster,
7546                         default_config: UserConfig::default(),
7547                         channel_monitors: &mut channel_monitors,
7548                 }).unwrap().1
7549         };
7550         nodes[0].node = &node_state_0;
7551         assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7552         nodes[0].chain_monitor = &monitor;
7553         nodes[0].chain_source = &chain_source;
7554
7555         check_added_monitors!(nodes[0], 1);
7556
7557         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7558         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7559
7560         let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7561
7562         // Check we don't broadcast any transactions following learning of per_commitment_point from B
7563         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7564         check_added_monitors!(nodes[0], 1);
7565
7566         {
7567                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7568                 assert_eq!(node_txn.len(), 0);
7569         }
7570
7571         let mut reestablish_1 = Vec::with_capacity(1);
7572         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7573                 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7574                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7575                         reestablish_1.push(msg.clone());
7576                 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7577                 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7578                         match action {
7579                                 &ErrorAction::SendErrorMessage { ref msg } => {
7580                                         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");
7581                                 },
7582                                 _ => panic!("Unexpected event!"),
7583                         }
7584                 } else {
7585                         panic!("Unexpected event")
7586                 }
7587         }
7588
7589         // Check we close channel detecting A is fallen-behind
7590         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7591         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7592         check_added_monitors!(nodes[1], 1);
7593
7594
7595         // Check A is able to claim to_remote output
7596         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7597         assert_eq!(node_txn.len(), 1);
7598         check_spends!(node_txn[0], chan.3);
7599         assert_eq!(node_txn[0].output.len(), 2);
7600         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
7601         connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[0].clone()]}, 0);
7602         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 0, true, header.bitcoin_hash());
7603         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
7604         assert_eq!(spend_txn.len(), 1);
7605         check_spends!(spend_txn[0], node_txn[0]);
7606 }
7607
7608 #[test]
7609 fn test_check_htlc_underpaying() {
7610         // Send payment through A -> B but A is maliciously
7611         // sending a probe payment (i.e less than expected value0
7612         // to B, B should refuse payment.
7613
7614         let chanmon_cfgs = create_chanmon_cfgs(2);
7615         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7616         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7617         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7618
7619         // Create some initial channels
7620         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7621
7622         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 10_000);
7623
7624         // Node 3 is expecting payment of 100_000 but receive 10_000,
7625         // fail htlc like we didn't know the preimage.
7626         nodes[1].node.claim_funds(payment_preimage, &None, 100_000);
7627         nodes[1].node.process_pending_htlc_forwards();
7628
7629         let events = nodes[1].node.get_and_clear_pending_msg_events();
7630         assert_eq!(events.len(), 1);
7631         let (update_fail_htlc, commitment_signed) = match events[0] {
7632                 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 } } => {
7633                         assert!(update_add_htlcs.is_empty());
7634                         assert!(update_fulfill_htlcs.is_empty());
7635                         assert_eq!(update_fail_htlcs.len(), 1);
7636                         assert!(update_fail_malformed_htlcs.is_empty());
7637                         assert!(update_fee.is_none());
7638                         (update_fail_htlcs[0].clone(), commitment_signed)
7639                 },
7640                 _ => panic!("Unexpected event"),
7641         };
7642         check_added_monitors!(nodes[1], 1);
7643
7644         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7645         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7646
7647         // 10_000 msat as u64, followed by a height of 99 as u32
7648         let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7649         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(99));
7650         expect_payment_failed!(nodes[0], payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7651         nodes[1].node.get_and_clear_pending_events();
7652 }
7653
7654 #[test]
7655 fn test_announce_disable_channels() {
7656         // Create 2 channels between A and B. Disconnect B. Call timer_chan_freshness_every_min and check for generated
7657         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7658
7659         let chanmon_cfgs = create_chanmon_cfgs(2);
7660         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7661         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7662         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7663
7664         let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7665         let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7666         let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7667
7668         // Disconnect peers
7669         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7670         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7671
7672         nodes[0].node.timer_chan_freshness_every_min(); // dirty -> stagged
7673         nodes[0].node.timer_chan_freshness_every_min(); // staged -> fresh
7674         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7675         assert_eq!(msg_events.len(), 3);
7676         for e in msg_events {
7677                 match e {
7678                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7679                                 let short_id = msg.contents.short_channel_id;
7680                                 // Check generated channel_update match list in PendingChannelUpdate
7681                                 if short_id != short_id_1 && short_id != short_id_2 && short_id != short_id_3 {
7682                                         panic!("Generated ChannelUpdate for wrong chan!");
7683                                 }
7684                         },
7685                         _ => panic!("Unexpected event"),
7686                 }
7687         }
7688         // Reconnect peers
7689         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7690         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7691         assert_eq!(reestablish_1.len(), 3);
7692         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7693         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7694         assert_eq!(reestablish_2.len(), 3);
7695
7696         // Reestablish chan_1
7697         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7698         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7699         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7700         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7701         // Reestablish chan_2
7702         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7703         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7704         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7705         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7706         // Reestablish chan_3
7707         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7708         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7709         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7710         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7711
7712         nodes[0].node.timer_chan_freshness_every_min();
7713         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7714 }
7715
7716 #[test]
7717 fn test_bump_penalty_txn_on_revoked_commitment() {
7718         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7719         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7720
7721         let chanmon_cfgs = create_chanmon_cfgs(2);
7722         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7723         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7724         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7725
7726         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7727         let logger = test_utils::TestLogger::new();
7728
7729
7730         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7731         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
7732         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();
7733         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7734
7735         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7736         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7737         assert_eq!(revoked_txn[0].output.len(), 4);
7738         assert_eq!(revoked_txn[0].input.len(), 1);
7739         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7740         let revoked_txid = revoked_txn[0].txid();
7741
7742         let mut penalty_sum = 0;
7743         for outp in revoked_txn[0].output.iter() {
7744                 if outp.script_pubkey.is_v0_p2wsh() {
7745                         penalty_sum += outp.value;
7746                 }
7747         }
7748
7749         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7750         let header_114 = connect_blocks(&nodes[1], 114, 0, false, Default::default());
7751
7752         // Actually revoke tx by claiming a HTLC
7753         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7754         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7755         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] }, 115);
7756         check_added_monitors!(nodes[1], 1);
7757
7758         // One or more justice tx should have been broadcast, check it
7759         let penalty_1;
7760         let feerate_1;
7761         {
7762                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7763                 assert_eq!(node_txn.len(), 3); // justice tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout (broadcasted from ChannelManager)
7764                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7765                 assert_eq!(node_txn[0].output.len(), 1);
7766                 check_spends!(node_txn[0], revoked_txn[0]);
7767                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7768                 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7769                 penalty_1 = node_txn[0].txid();
7770                 node_txn.clear();
7771         };
7772
7773         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7774         let header = connect_blocks(&nodes[1], 3, 115,  true, header.bitcoin_hash());
7775         let mut penalty_2 = penalty_1;
7776         let mut feerate_2 = 0;
7777         {
7778                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7779                 assert_eq!(node_txn.len(), 1);
7780                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7781                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7782                         assert_eq!(node_txn[0].output.len(), 1);
7783                         check_spends!(node_txn[0], revoked_txn[0]);
7784                         penalty_2 = node_txn[0].txid();
7785                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7786                         assert_ne!(penalty_2, penalty_1);
7787                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7788                         feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7789                         // Verify 25% bump heuristic
7790                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7791                         node_txn.clear();
7792                 }
7793         }
7794         assert_ne!(feerate_2, 0);
7795
7796         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7797         connect_blocks(&nodes[1], 3, 118, true, header);
7798         let penalty_3;
7799         let mut feerate_3 = 0;
7800         {
7801                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7802                 assert_eq!(node_txn.len(), 1);
7803                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7804                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7805                         assert_eq!(node_txn[0].output.len(), 1);
7806                         check_spends!(node_txn[0], revoked_txn[0]);
7807                         penalty_3 = node_txn[0].txid();
7808                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7809                         assert_ne!(penalty_3, penalty_2);
7810                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7811                         feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7812                         // Verify 25% bump heuristic
7813                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7814                         node_txn.clear();
7815                 }
7816         }
7817         assert_ne!(feerate_3, 0);
7818
7819         nodes[1].node.get_and_clear_pending_events();
7820         nodes[1].node.get_and_clear_pending_msg_events();
7821 }
7822
7823 #[test]
7824 fn test_bump_penalty_txn_on_revoked_htlcs() {
7825         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7826         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7827
7828         let chanmon_cfgs = create_chanmon_cfgs(2);
7829         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7830         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7831         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7832
7833         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7834         // Lock HTLC in both directions
7835         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3_000_000).0;
7836         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7837
7838         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7839         assert_eq!(revoked_local_txn[0].input.len(), 1);
7840         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7841
7842         // Revoke local commitment tx
7843         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7844
7845         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7846         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7847         connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
7848         check_closed_broadcast!(nodes[1], false);
7849         check_added_monitors!(nodes[1], 1);
7850
7851         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7852         assert_eq!(revoked_htlc_txn.len(), 4);
7853         if revoked_htlc_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7854                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7855                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7856                 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7857                 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7858                 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7859         } else if revoked_htlc_txn[1].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7860                 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7861                 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7862                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7863                 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7864                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7865         }
7866
7867         // Broadcast set of revoked txn on A
7868         let header_128 = connect_blocks(&nodes[0], 128, 0, true, header.bitcoin_hash());
7869         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7870
7871         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7872         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()] }, 129);
7873         let first;
7874         let feerate_1;
7875         let penalty_txn;
7876         {
7877                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7878                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7879                 // Verify claim tx are spending revoked HTLC txn
7880                 assert_eq!(node_txn[3].input.len(), 2);
7881                 assert_eq!(node_txn[3].output.len(), 1);
7882                 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7883                 first = node_txn[3].txid();
7884                 // Store both feerates for later comparison
7885                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7886                 feerate_1 = fee_1 * 1000 / node_txn[3].get_weight() as u64;
7887                 penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7888                 node_txn.clear();
7889         }
7890
7891         // Connect three more block to see if bumped penalty are issued for HTLC txn
7892         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7893         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn }, 130);
7894         {
7895                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7896                 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7897
7898                 check_spends!(node_txn[0], revoked_local_txn[0]);
7899                 check_spends!(node_txn[1], revoked_local_txn[0]);
7900
7901                 node_txn.clear();
7902         };
7903
7904         // Few more blocks to confirm penalty txn
7905         let header_135 = connect_blocks(&nodes[0], 5, 130, true, header_130.bitcoin_hash());
7906         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7907         let header_144 = connect_blocks(&nodes[0], 9, 135, true, header_135);
7908         let node_txn = {
7909                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7910                 assert_eq!(node_txn.len(), 1);
7911
7912                 assert_eq!(node_txn[0].input.len(), 2);
7913                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7914                 // Verify bumped tx is different and 25% bump heuristic
7915                 assert_ne!(first, node_txn[0].txid());
7916                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7917                 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7918                 assert!(feerate_2 * 100 > feerate_1 * 125);
7919                 let txn = vec![node_txn[0].clone()];
7920                 node_txn.clear();
7921                 txn
7922         };
7923         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7924         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7925         connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn }, 145);
7926         connect_blocks(&nodes[0], 20, 145, true, header_145.bitcoin_hash());
7927         {
7928                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7929                 // We verify than no new transaction has been broadcast because previously
7930                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7931                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7932                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7933                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7934                 // up bumped justice generation.
7935                 assert_eq!(node_txn.len(), 0);
7936                 node_txn.clear();
7937         }
7938         check_closed_broadcast!(nodes[0], false);
7939         check_added_monitors!(nodes[0], 1);
7940 }
7941
7942 #[test]
7943 fn test_bump_penalty_txn_on_remote_commitment() {
7944         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7945         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7946
7947         // Create 2 HTLCs
7948         // Provide preimage for one
7949         // Check aggregation
7950
7951         let chanmon_cfgs = create_chanmon_cfgs(2);
7952         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7953         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7954         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7955
7956         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7957         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7958         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7959
7960         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7961         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7962         assert_eq!(remote_txn[0].output.len(), 4);
7963         assert_eq!(remote_txn[0].input.len(), 1);
7964         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7965
7966         // Claim a HTLC without revocation (provide B monitor with preimage)
7967         nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000);
7968         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7969         connect_block(&nodes[1], &Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
7970         check_added_monitors!(nodes[1], 2);
7971
7972         // One or more claim tx should have been broadcast, check it
7973         let timeout;
7974         let preimage;
7975         let feerate_timeout;
7976         let feerate_preimage;
7977         {
7978                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7979                 assert_eq!(node_txn.len(), 5); // 2 * claim tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout + local HTLC-success (broadcasted from ChannelManager)
7980                 assert_eq!(node_txn[0].input.len(), 1);
7981                 assert_eq!(node_txn[1].input.len(), 1);
7982                 check_spends!(node_txn[0], remote_txn[0]);
7983                 check_spends!(node_txn[1], remote_txn[0]);
7984                 check_spends!(node_txn[2], chan.3);
7985                 check_spends!(node_txn[3], node_txn[2]);
7986                 check_spends!(node_txn[4], node_txn[2]);
7987                 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7988                         timeout = node_txn[0].txid();
7989                         let index = node_txn[0].input[0].previous_output.vout;
7990                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7991                         feerate_timeout = fee * 1000 / node_txn[0].get_weight() as u64;
7992
7993                         preimage = node_txn[1].txid();
7994                         let index = node_txn[1].input[0].previous_output.vout;
7995                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7996                         feerate_preimage = fee * 1000 / node_txn[1].get_weight() as u64;
7997                 } else {
7998                         timeout = node_txn[1].txid();
7999                         let index = node_txn[1].input[0].previous_output.vout;
8000                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
8001                         feerate_timeout = fee * 1000 / node_txn[1].get_weight() as u64;
8002
8003                         preimage = node_txn[0].txid();
8004                         let index = node_txn[0].input[0].previous_output.vout;
8005                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8006                         feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
8007                 }
8008                 node_txn.clear();
8009         };
8010         assert_ne!(feerate_timeout, 0);
8011         assert_ne!(feerate_preimage, 0);
8012
8013         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
8014         connect_blocks(&nodes[1], 15, 1,  true, header.bitcoin_hash());
8015         {
8016                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8017                 assert_eq!(node_txn.len(), 2);
8018                 assert_eq!(node_txn[0].input.len(), 1);
8019                 assert_eq!(node_txn[1].input.len(), 1);
8020                 check_spends!(node_txn[0], remote_txn[0]);
8021                 check_spends!(node_txn[1], remote_txn[0]);
8022                 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
8023                         let index = node_txn[0].input[0].previous_output.vout;
8024                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8025                         let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
8026                         assert!(new_feerate * 100 > feerate_timeout * 125);
8027                         assert_ne!(timeout, node_txn[0].txid());
8028
8029                         let index = node_txn[1].input[0].previous_output.vout;
8030                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
8031                         let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
8032                         assert!(new_feerate * 100 > feerate_preimage * 125);
8033                         assert_ne!(preimage, node_txn[1].txid());
8034                 } else {
8035                         let index = node_txn[1].input[0].previous_output.vout;
8036                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
8037                         let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
8038                         assert!(new_feerate * 100 > feerate_timeout * 125);
8039                         assert_ne!(timeout, node_txn[1].txid());
8040
8041                         let index = node_txn[0].input[0].previous_output.vout;
8042                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8043                         let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
8044                         assert!(new_feerate * 100 > feerate_preimage * 125);
8045                         assert_ne!(preimage, node_txn[0].txid());
8046                 }
8047                 node_txn.clear();
8048         }
8049
8050         nodes[1].node.get_and_clear_pending_events();
8051         nodes[1].node.get_and_clear_pending_msg_events();
8052 }
8053
8054 #[test]
8055 fn test_set_outpoints_partial_claiming() {
8056         // - remote party claim tx, new bump tx
8057         // - disconnect remote claiming tx, new bump
8058         // - disconnect tx, see no tx anymore
8059         let chanmon_cfgs = create_chanmon_cfgs(2);
8060         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8061         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8062         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8063
8064         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8065         let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
8066         let payment_preimage_2 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
8067
8068         // Remote commitment txn with 4 outputs: to_local, to_remote, 2 outgoing HTLC
8069         let remote_txn = get_local_commitment_txn!(nodes[1], chan.2);
8070         assert_eq!(remote_txn.len(), 3);
8071         assert_eq!(remote_txn[0].output.len(), 4);
8072         assert_eq!(remote_txn[0].input.len(), 1);
8073         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
8074         check_spends!(remote_txn[1], remote_txn[0]);
8075         check_spends!(remote_txn[2], remote_txn[0]);
8076
8077         // Connect blocks on node A to advance height towards TEST_FINAL_CLTV
8078         let prev_header_100 = connect_blocks(&nodes[1], 100, 0, false, Default::default());
8079         // Provide node A with both preimage
8080         nodes[0].node.claim_funds(payment_preimage_1, &None, 3_000_000);
8081         nodes[0].node.claim_funds(payment_preimage_2, &None, 3_000_000);
8082         check_added_monitors!(nodes[0], 2);
8083         nodes[0].node.get_and_clear_pending_events();
8084         nodes[0].node.get_and_clear_pending_msg_events();
8085
8086         // Connect blocks on node A commitment transaction
8087         let header = BlockHeader { version: 0x20000000, prev_blockhash: prev_header_100, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8088         connect_block(&nodes[0], &Block { header, txdata: vec![remote_txn[0].clone()] }, 101);
8089         check_closed_broadcast!(nodes[0], false);
8090         check_added_monitors!(nodes[0], 1);
8091         // Verify node A broadcast tx claiming both HTLCs
8092         {
8093                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8094                 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-Success*2
8095                 assert_eq!(node_txn.len(), 4);
8096                 check_spends!(node_txn[0], remote_txn[0]);
8097                 check_spends!(node_txn[1], chan.3);
8098                 check_spends!(node_txn[2], node_txn[1]);
8099                 check_spends!(node_txn[3], node_txn[1]);
8100                 assert_eq!(node_txn[0].input.len(), 2);
8101                 node_txn.clear();
8102         }
8103
8104         // Connect blocks on node B
8105         connect_blocks(&nodes[1], 135, 0, false, Default::default());
8106         check_closed_broadcast!(nodes[1], false);
8107         check_added_monitors!(nodes[1], 1);
8108         // Verify node B broadcast 2 HTLC-timeout txn
8109         let partial_claim_tx = {
8110                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8111                 assert_eq!(node_txn.len(), 3);
8112                 check_spends!(node_txn[1], node_txn[0]);
8113                 check_spends!(node_txn[2], node_txn[0]);
8114                 assert_eq!(node_txn[1].input.len(), 1);
8115                 assert_eq!(node_txn[2].input.len(), 1);
8116                 node_txn[1].clone()
8117         };
8118
8119         // Broadcast partial claim on node A, should regenerate a claiming tx with HTLC dropped
8120         let header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8121         connect_block(&nodes[0], &Block { header, txdata: vec![partial_claim_tx.clone()] }, 102);
8122         {
8123                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8124                 assert_eq!(node_txn.len(), 1);
8125                 check_spends!(node_txn[0], remote_txn[0]);
8126                 assert_eq!(node_txn[0].input.len(), 1); //dropped HTLC
8127                 node_txn.clear();
8128         }
8129         nodes[0].node.get_and_clear_pending_msg_events();
8130
8131         // Disconnect last block on node A, should regenerate a claiming tx with HTLC dropped
8132         disconnect_block(&nodes[0], &header, 102);
8133         {
8134                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8135                 assert_eq!(node_txn.len(), 1);
8136                 check_spends!(node_txn[0], remote_txn[0]);
8137                 assert_eq!(node_txn[0].input.len(), 2); //resurrected HTLC
8138                 node_txn.clear();
8139         }
8140
8141         //// Disconnect one more block and then reconnect multiple no transaction should be generated
8142         disconnect_block(&nodes[0], &header, 101);
8143         connect_blocks(&nodes[1], 15, 101, false, prev_header_100);
8144         {
8145                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8146                 assert_eq!(node_txn.len(), 0);
8147                 node_txn.clear();
8148         }
8149 }
8150
8151 #[test]
8152 fn test_counterparty_raa_skip_no_crash() {
8153         // Previously, if our counterparty sent two RAAs in a row without us having provided a
8154         // commitment transaction, we would have happily carried on and provided them the next
8155         // commitment transaction based on one RAA forward. This would probably eventually have led to
8156         // channel closure, but it would not have resulted in funds loss. Still, our
8157         // EnforcingChannelKeys would have paniced as it doesn't like jumps into the future. Here, we
8158         // check simply that the channel is closed in response to such an RAA, but don't check whether
8159         // we decide to punish our counterparty for revoking their funds (as we don't currently
8160         // implement that).
8161         let chanmon_cfgs = create_chanmon_cfgs(2);
8162         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8163         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8164         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8165         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8166
8167         let mut guard = nodes[0].node.channel_state.lock().unwrap();
8168         let local_keys = &guard.by_id.get_mut(&channel_id).unwrap().local_keys;
8169         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8170         let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8171                 &SecretKey::from_slice(&local_keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8172         let per_commitment_secret = local_keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8173
8174         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8175                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8176         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8177         check_added_monitors!(nodes[1], 1);
8178 }
8179
8180 #[test]
8181 fn test_bump_txn_sanitize_tracking_maps() {
8182         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8183         // verify we clean then right after expiration of ANTI_REORG_DELAY.
8184
8185         let chanmon_cfgs = create_chanmon_cfgs(2);
8186         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8187         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8188         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8189
8190         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8191         // Lock HTLC in both directions
8192         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8193         route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8194
8195         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8196         assert_eq!(revoked_local_txn[0].input.len(), 1);
8197         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8198
8199         // Revoke local commitment tx
8200         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 9_000_000);
8201
8202         // Broadcast set of revoked txn on A
8203         let header_128 = connect_blocks(&nodes[0], 128, 0,  false, Default::default());
8204         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8205
8206         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8207         connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_local_txn[0].clone()] }, 129);
8208         check_closed_broadcast!(nodes[0], false);
8209         check_added_monitors!(nodes[0], 1);
8210         let penalty_txn = {
8211                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8212                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8213                 check_spends!(node_txn[0], revoked_local_txn[0]);
8214                 check_spends!(node_txn[1], revoked_local_txn[0]);
8215                 check_spends!(node_txn[2], revoked_local_txn[0]);
8216                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8217                 node_txn.clear();
8218                 penalty_txn
8219         };
8220         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8221         connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn }, 130);
8222         connect_blocks(&nodes[0], 5, 130,  false, header_130.bitcoin_hash());
8223         {
8224                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap();
8225                 if let Some(monitor) = monitors.get(&OutPoint { txid: chan.3.txid(), index: 0 }) {
8226                         assert!(monitor.onchain_tx_handler.pending_claim_requests.is_empty());
8227                         assert!(monitor.onchain_tx_handler.claimable_outpoints.is_empty());
8228                 }
8229         }
8230 }
8231
8232 #[test]
8233 fn test_override_channel_config() {
8234         let chanmon_cfgs = create_chanmon_cfgs(2);
8235         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8236         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8237         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8238
8239         // Node0 initiates a channel to node1 using the override config.
8240         let mut override_config = UserConfig::default();
8241         override_config.own_channel_config.our_to_self_delay = 200;
8242
8243         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8244
8245         // Assert the channel created by node0 is using the override config.
8246         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8247         assert_eq!(res.channel_flags, 0);
8248         assert_eq!(res.to_self_delay, 200);
8249 }
8250
8251 #[test]
8252 fn test_override_0msat_htlc_minimum() {
8253         let mut zero_config = UserConfig::default();
8254         zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8255         let chanmon_cfgs = create_chanmon_cfgs(2);
8256         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8257         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8258         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8259
8260         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8261         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8262         assert_eq!(res.htlc_minimum_msat, 1);
8263
8264         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8265         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8266         assert_eq!(res.htlc_minimum_msat, 1);
8267 }
8268
8269 #[test]
8270 fn test_simple_payment_secret() {
8271         // Simple test of sending a payment with a payment_secret present. This does not use any AMP
8272         // features, however.
8273         let chanmon_cfgs = create_chanmon_cfgs(3);
8274         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8275         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8276         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8277
8278         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8279         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
8280         let logger = test_utils::TestLogger::new();
8281
8282         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8283         let payment_secret = PaymentSecret([0xdb; 32]);
8284         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8285         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();
8286         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2]]], 100000, payment_hash, Some(payment_secret.clone()));
8287         // Claiming with all the correct values but the wrong secret should result in nothing...
8288         assert_eq!(nodes[2].node.claim_funds(payment_preimage, &None, 100_000), false);
8289         assert_eq!(nodes[2].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 100_000), false);
8290         // ...but with the right secret we should be able to claim all the way back
8291         claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage, Some(payment_secret.clone()), 100_000);
8292 }
8293
8294 #[test]
8295 fn test_simple_mpp() {
8296         // Simple test of sending a multi-path payment.
8297         let chanmon_cfgs = create_chanmon_cfgs(4);
8298         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8299         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8300         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8301
8302         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8303         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8304         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8305         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8306         let logger = test_utils::TestLogger::new();
8307
8308         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8309         let payment_secret = PaymentSecret([0xdb; 32]);
8310         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8311         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();
8312         let path = route.paths[0].clone();
8313         route.paths.push(path);
8314         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8315         route.paths[0][0].short_channel_id = chan_1_id;
8316         route.paths[0][1].short_channel_id = chan_3_id;
8317         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8318         route.paths[1][0].short_channel_id = chan_2_id;
8319         route.paths[1][1].short_channel_id = chan_4_id;
8320         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, Some(payment_secret.clone()));
8321         // Claiming with all the correct values but the wrong secret should result in nothing...
8322         assert_eq!(nodes[3].node.claim_funds(payment_preimage, &None, 200_000), false);
8323         assert_eq!(nodes[3].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 200_000), false);
8324         // ...but with the right secret we should be able to claim all the way back
8325         claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage, Some(payment_secret), 200_000);
8326 }
8327
8328 #[test]
8329 fn test_update_err_monitor_lockdown() {
8330         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8331         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8332         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8333         //
8334         // This scenario may happen in a watchtower setup, where watchtower process a block height
8335         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8336         // commitment at same time.
8337
8338         let chanmon_cfgs = create_chanmon_cfgs(2);
8339         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8340         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8341         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8342
8343         // Create some initial channel
8344         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8345         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8346
8347         // Rebalance the network to generate htlc in the two directions
8348         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8349
8350         // Route a HTLC from node 0 to node 1 (but don't settle)
8351         let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8352
8353         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8354         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8355         let watchtower = {
8356                 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap();
8357                 let monitor = monitors.get(&outpoint).unwrap();
8358                 let mut w = test_utils::TestVecWriter(Vec::new());
8359                 monitor.write_for_disk(&mut w).unwrap();
8360                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
8361                                 &mut ::std::io::Cursor::new(&w.0)).unwrap().1;
8362                 assert!(new_monitor == *monitor);
8363                 let watchtower = test_utils::TestChainMonitor::new(&chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator);
8364                 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8365                 watchtower
8366         };
8367         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8368         watchtower.chain_monitor.block_connected(&header, &[], 200);
8369
8370         // Try to update ChannelMonitor
8371         assert!(nodes[1].node.claim_funds(preimage, &None, 9_000_000));
8372         check_added_monitors!(nodes[1], 1);
8373         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8374         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8375         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8376         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8377                 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8378                         if let Err(_) =  watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8379                         if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8380                 } else { assert!(false); }
8381         } else { assert!(false); };
8382         // Our local monitor is in-sync and hasn't processed yet timeout
8383         check_added_monitors!(nodes[0], 1);
8384         let events = nodes[0].node.get_and_clear_pending_events();
8385         assert_eq!(events.len(), 1);
8386 }