Merge pull request #374 from dongcarl/2019-08-channel-open-sanity
[rust-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::transaction::OutPoint;
6 use chain::chaininterface::{ChainListener, ChainWatchInterface, ChainWatchInterfaceUtil};
7 use chain::keysinterface::{KeysInterface, SpendableOutputDescriptor, KeysManager};
8 use chain::keysinterface;
9 use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
10 use ln::channelmanager::{ChannelManager,ChannelManagerReadArgs,HTLCForwardInfo,RAACommitmentOrder, PaymentPreimage, PaymentHash, BREAKDOWN_TIMEOUT};
11 use ln::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ManyChannelMonitor, ANTI_REORG_DELAY};
12 use ln::channel::{ACCEPTED_HTLC_SCRIPT_WEIGHT, OFFERED_HTLC_SCRIPT_WEIGHT, Channel, ChannelError};
13 use ln::onion_utils;
14 use ln::router::{Route, RouteHop};
15 use ln::msgs;
16 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler,HTLCFailChannelUpdate, LocalFeatures, ErrorAction};
17 use util::test_utils;
18 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
19 use util::errors::APIError;
20 use util::ser::{Writeable, ReadableArgs};
21 use util::config::UserConfig;
22 use util::logger::Logger;
23
24 use bitcoin::util::hash::BitcoinHash;
25 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
26 use bitcoin::util::bip143;
27 use bitcoin::util::address::Address;
28 use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
29 use bitcoin::blockdata::block::{Block, BlockHeader};
30 use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType, OutPoint as BitcoinOutPoint};
31 use bitcoin::blockdata::script::{Builder, Script};
32 use bitcoin::blockdata::opcodes;
33 use bitcoin::blockdata::constants::genesis_block;
34 use bitcoin::network::constants::Network;
35
36 use bitcoin_hashes::sha256::Hash as Sha256;
37 use bitcoin_hashes::Hash;
38
39 use secp256k1::{Secp256k1, Message};
40 use secp256k1::key::{PublicKey,SecretKey};
41
42 use std::collections::{BTreeSet, HashMap, HashSet};
43 use std::default::Default;
44 use std::sync::{Arc, Mutex};
45 use std::sync::atomic::Ordering;
46 use std::mem;
47
48 use rand::{thread_rng, Rng};
49
50 use ln::functional_test_utils::*;
51
52 #[test]
53 fn test_insane_channel_opens() {
54         // Stand up a network of 2 nodes
55         let nodes = create_network(2, &[None, None]);
56
57         // Instantiate channel parameters where we push the maximum msats given our
58         // funding satoshis
59         let channel_value_sat = 31337; // same as funding satoshis
60         let channel_reserve_satoshis = Channel::get_our_channel_reserve_satoshis(channel_value_sat);
61         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
62
63         // Have node0 initiate a channel to node1 with aforementioned parameters
64         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42).unwrap();
65
66         // Extract the channel open message from node0 to node1
67         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
68
69         // Test helper that asserts we get the correct error string given a mutator
70         // that supposedly makes the channel open message insane
71         let insane_open_helper = |expected_error_str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
72                 match nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), LocalFeatures::new(), &message_mutator(open_channel_message.clone())) {
73                         Err(msgs::HandleError{ err: error_str, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) => {
74                                 assert_eq!(error_str, expected_error_str, "unexpected HandleError string (expected `{}`, actual `{}`)", expected_error_str, error_str)
75                         },
76                         Err(msgs::HandleError{..}) => {panic!("unexpected HandleError action")},
77                         _ => panic!("insane OpenChannel message was somehow Ok"),
78                 }
79         };
80
81         use ln::channel::MAX_FUNDING_SATOSHIS;
82         use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
83
84         // Test all mutations that would make the channel open message insane
85         insane_open_helper("funding value > 2^24", |mut msg| { msg.funding_satoshis = MAX_FUNDING_SATOSHIS; msg });
86
87         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
88
89         insane_open_helper("push_msat larger than funding value", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
90
91         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
92
93         insane_open_helper("Bogus; channel reserve is less than dust limit", |mut msg| { msg.dust_limit_satoshis = msg.channel_reserve_satoshis + 1; msg });
94
95         insane_open_helper("Minimum htlc value is full channel value", |mut msg| { msg.htlc_minimum_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000; msg });
96
97         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 });
98
99         insane_open_helper("0 max_accpted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
100
101         insane_open_helper("max_accpted_htlcs > 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
102 }
103
104 #[test]
105 fn test_async_inbound_update_fee() {
106         let mut nodes = create_network(2, &[None, None]);
107         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
108         let channel_id = chan.2;
109
110         // balancing
111         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
112
113         // A                                        B
114         // update_fee                            ->
115         // send (1) commitment_signed            -.
116         //                                       <- update_add_htlc/commitment_signed
117         // send (2) RAA (awaiting remote revoke) -.
118         // (1) commitment_signed is delivered    ->
119         //                                       .- send (3) RAA (awaiting remote revoke)
120         // (2) RAA is delivered                  ->
121         //                                       .- send (4) commitment_signed
122         //                                       <- (3) RAA is delivered
123         // send (5) commitment_signed            -.
124         //                                       <- (4) commitment_signed is delivered
125         // send (6) RAA                          -.
126         // (5) commitment_signed is delivered    ->
127         //                                       <- RAA
128         // (6) RAA is delivered                  ->
129
130         // First nodes[0] generates an update_fee
131         nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
132         check_added_monitors!(nodes[0], 1);
133
134         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
135         assert_eq!(events_0.len(), 1);
136         let (update_msg, commitment_signed) = match events_0[0] { // (1)
137                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
138                         (update_fee.as_ref(), commitment_signed)
139                 },
140                 _ => panic!("Unexpected event"),
141         };
142
143         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
144
145         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
146         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
147         nodes[1].node.send_payment(nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV).unwrap(), our_payment_hash).unwrap();
148         check_added_monitors!(nodes[1], 1);
149
150         let payment_event = {
151                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
152                 assert_eq!(events_1.len(), 1);
153                 SendEvent::from_event(events_1.remove(0))
154         };
155         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
156         assert_eq!(payment_event.msgs.len(), 1);
157
158         // ...now when the messages get delivered everyone should be happy
159         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
160         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
161         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
162         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
163         check_added_monitors!(nodes[0], 1);
164
165         // deliver(1), generate (3):
166         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
167         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
168         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
169         check_added_monitors!(nodes[1], 1);
170
171         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap(); // deliver (2)
172         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
173         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
174         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
175         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
176         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
177         assert!(bs_update.update_fee.is_none()); // (4)
178         check_added_monitors!(nodes[1], 1);
179
180         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap(); // deliver (3)
181         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
182         assert!(as_update.update_add_htlcs.is_empty()); // (5)
183         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
184         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
185         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
186         assert!(as_update.update_fee.is_none()); // (5)
187         check_added_monitors!(nodes[0], 1);
188
189         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed).unwrap(); // deliver (4)
190         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
191         // only (6) so get_event_msg's assert(len == 1) passes
192         check_added_monitors!(nodes[0], 1);
193
194         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed).unwrap(); // deliver (5)
195         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
196         check_added_monitors!(nodes[1], 1);
197
198         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
199         check_added_monitors!(nodes[0], 1);
200
201         let events_2 = nodes[0].node.get_and_clear_pending_events();
202         assert_eq!(events_2.len(), 1);
203         match events_2[0] {
204                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
205                 _ => panic!("Unexpected event"),
206         }
207
208         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap(); // deliver (6)
209         check_added_monitors!(nodes[1], 1);
210 }
211
212 #[test]
213 fn test_update_fee_unordered_raa() {
214         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
215         // crash in an earlier version of the update_fee patch)
216         let mut nodes = create_network(2, &[None, None]);
217         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
218         let channel_id = chan.2;
219
220         // balancing
221         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
222
223         // First nodes[0] generates an update_fee
224         nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
225         check_added_monitors!(nodes[0], 1);
226
227         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
228         assert_eq!(events_0.len(), 1);
229         let update_msg = match events_0[0] { // (1)
230                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
231                         update_fee.as_ref()
232                 },
233                 _ => panic!("Unexpected event"),
234         };
235
236         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
237
238         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
239         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
240         nodes[1].node.send_payment(nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV).unwrap(), our_payment_hash).unwrap();
241         check_added_monitors!(nodes[1], 1);
242
243         let payment_event = {
244                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
245                 assert_eq!(events_1.len(), 1);
246                 SendEvent::from_event(events_1.remove(0))
247         };
248         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
249         assert_eq!(payment_event.msgs.len(), 1);
250
251         // ...now when the messages get delivered everyone should be happy
252         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
253         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
254         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
255         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
256         check_added_monitors!(nodes[0], 1);
257
258         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap(); // deliver (2)
259         check_added_monitors!(nodes[1], 1);
260
261         // We can't continue, sadly, because our (1) now has a bogus signature
262 }
263
264 #[test]
265 fn test_multi_flight_update_fee() {
266         let nodes = create_network(2, &[None, None]);
267         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
268         let channel_id = chan.2;
269
270         // A                                        B
271         // update_fee/commitment_signed          ->
272         //                                       .- send (1) RAA and (2) commitment_signed
273         // update_fee (never committed)          ->
274         // (3) update_fee                        ->
275         // We have to manually generate the above update_fee, it is allowed by the protocol but we
276         // don't track which updates correspond to which revoke_and_ack responses so we're in
277         // AwaitingRAA mode and will not generate the update_fee yet.
278         //                                       <- (1) RAA delivered
279         // (3) is generated and send (4) CS      -.
280         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
281         // know the per_commitment_point to use for it.
282         //                                       <- (2) commitment_signed delivered
283         // revoke_and_ack                        ->
284         //                                          B should send no response here
285         // (4) commitment_signed delivered       ->
286         //                                       <- RAA/commitment_signed delivered
287         // revoke_and_ack                        ->
288
289         // First nodes[0] generates an update_fee
290         let initial_feerate = get_feerate!(nodes[0], channel_id);
291         nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
292         check_added_monitors!(nodes[0], 1);
293
294         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
295         assert_eq!(events_0.len(), 1);
296         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
297                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
298                         (update_fee.as_ref().unwrap(), commitment_signed)
299                 },
300                 _ => panic!("Unexpected event"),
301         };
302
303         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
304         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1).unwrap();
305         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1).unwrap();
306         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
307         check_added_monitors!(nodes[1], 1);
308
309         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
310         // transaction:
311         nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
312         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
313         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
314
315         // Create the (3) update_fee message that nodes[0] will generate before it does...
316         let mut update_msg_2 = msgs::UpdateFee {
317                 channel_id: update_msg_1.channel_id.clone(),
318                 feerate_per_kw: (initial_feerate + 30) as u32,
319         };
320
321         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
322
323         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
324         // Deliver (3)
325         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
326
327         // Deliver (1), generating (3) and (4)
328         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg).unwrap();
329         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
330         check_added_monitors!(nodes[0], 1);
331         assert!(as_second_update.update_add_htlcs.is_empty());
332         assert!(as_second_update.update_fulfill_htlcs.is_empty());
333         assert!(as_second_update.update_fail_htlcs.is_empty());
334         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
335         // Check that the update_fee newly generated matches what we delivered:
336         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
337         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
338
339         // Deliver (2) commitment_signed
340         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
341         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
342         check_added_monitors!(nodes[0], 1);
343         // No commitment_signed so get_event_msg's assert(len == 1) passes
344
345         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap();
346         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
347         check_added_monitors!(nodes[1], 1);
348
349         // Delever (4)
350         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed).unwrap();
351         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
352         check_added_monitors!(nodes[1], 1);
353
354         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
355         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
356         check_added_monitors!(nodes[0], 1);
357
358         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment).unwrap();
359         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
360         // No commitment_signed so get_event_msg's assert(len == 1) passes
361         check_added_monitors!(nodes[0], 1);
362
363         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap();
364         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
365         check_added_monitors!(nodes[1], 1);
366 }
367
368 #[test]
369 fn test_update_fee_vanilla() {
370         let nodes = create_network(2, &[None, None]);
371         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
372         let channel_id = chan.2;
373
374         let feerate = get_feerate!(nodes[0], channel_id);
375         nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
376         check_added_monitors!(nodes[0], 1);
377
378         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
379         assert_eq!(events_0.len(), 1);
380         let (update_msg, commitment_signed) = match events_0[0] {
381                         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 } } => {
382                         (update_fee.as_ref(), commitment_signed)
383                 },
384                 _ => panic!("Unexpected event"),
385         };
386         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
387
388         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
389         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
390         check_added_monitors!(nodes[1], 1);
391
392         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
393         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
394         check_added_monitors!(nodes[0], 1);
395
396         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
397         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
398         // No commitment_signed so get_event_msg's assert(len == 1) passes
399         check_added_monitors!(nodes[0], 1);
400
401         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
402         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
403         check_added_monitors!(nodes[1], 1);
404 }
405
406 #[test]
407 fn test_update_fee_that_funder_cannot_afford() {
408         let nodes = create_network(2, &[None, None]);
409         let channel_value = 1888;
410         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000, LocalFeatures::new(), LocalFeatures::new());
411         let channel_id = chan.2;
412
413         let feerate = 260;
414         nodes[0].node.update_fee(channel_id, feerate).unwrap();
415         check_added_monitors!(nodes[0], 1);
416         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
417
418         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap()).unwrap();
419
420         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
421
422         //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
423         //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
424         {
425                 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
426                 let chan = chan_lock.by_id.get(&channel_id).unwrap();
427
428                 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
429                 let num_htlcs = chan.last_local_commitment_txn[0].output.len() - 2;
430                 let total_fee: u64 = feerate * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
431                 let mut actual_fee = chan.last_local_commitment_txn[0].output.iter().fold(0, |acc, output| acc + output.value);
432                 actual_fee = channel_value - actual_fee;
433                 assert_eq!(total_fee, actual_fee);
434         } //drop the mutex
435
436         //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
437         //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
438         nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
439         check_added_monitors!(nodes[0], 1);
440
441         let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
442
443         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap()).unwrap();
444
445         //While producing the commitment_signed response after handling a received update_fee request the
446         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
447         //Should produce and error.
448         let err = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed).unwrap_err();
449
450         assert!(match err.err {
451                 "Funding remote cannot afford proposed new fee" => true,
452                 _ => false,
453         });
454
455         //clear the message we could not handle
456         nodes[1].node.get_and_clear_pending_msg_events();
457 }
458
459 #[test]
460 fn test_update_fee_with_fundee_update_add_htlc() {
461         let mut nodes = create_network(2, &[None, None]);
462         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
463         let channel_id = chan.2;
464
465         // balancing
466         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
467
468         let feerate = get_feerate!(nodes[0], channel_id);
469         nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
470         check_added_monitors!(nodes[0], 1);
471
472         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
473         assert_eq!(events_0.len(), 1);
474         let (update_msg, commitment_signed) = match events_0[0] {
475                         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 } } => {
476                         (update_fee.as_ref(), commitment_signed)
477                 },
478                 _ => panic!("Unexpected event"),
479         };
480         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
481         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
482         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
483         check_added_monitors!(nodes[1], 1);
484
485         let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 800000, TEST_FINAL_CLTV).unwrap();
486
487         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
488
489         // nothing happens since node[1] is in AwaitingRemoteRevoke
490         nodes[1].node.send_payment(route, our_payment_hash).unwrap();
491         {
492                 let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
493                 assert_eq!(added_monitors.len(), 0);
494                 added_monitors.clear();
495         }
496         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
497         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
498         // node[1] has nothing to do
499
500         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
501         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
502         check_added_monitors!(nodes[0], 1);
503
504         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
505         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
506         // No commitment_signed so get_event_msg's assert(len == 1) passes
507         check_added_monitors!(nodes[0], 1);
508         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
509         check_added_monitors!(nodes[1], 1);
510         // AwaitingRemoteRevoke ends here
511
512         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
513         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
514         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
515         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
516         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
517         assert_eq!(commitment_update.update_fee.is_none(), true);
518
519         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]).unwrap();
520         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
521         check_added_monitors!(nodes[0], 1);
522         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
523
524         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke).unwrap();
525         check_added_monitors!(nodes[1], 1);
526         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
527
528         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed).unwrap();
529         check_added_monitors!(nodes[1], 1);
530         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
531         // No commitment_signed so get_event_msg's assert(len == 1) passes
532
533         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke).unwrap();
534         check_added_monitors!(nodes[0], 1);
535         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
536
537         expect_pending_htlcs_forwardable!(nodes[0]);
538
539         let events = nodes[0].node.get_and_clear_pending_events();
540         assert_eq!(events.len(), 1);
541         match events[0] {
542                 Event::PaymentReceived { .. } => { },
543                 _ => panic!("Unexpected event"),
544         };
545
546         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
547
548         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
549         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
550         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
551 }
552
553 #[test]
554 fn test_update_fee() {
555         let nodes = create_network(2, &[None, None]);
556         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
557         let channel_id = chan.2;
558
559         // A                                        B
560         // (1) update_fee/commitment_signed      ->
561         //                                       <- (2) revoke_and_ack
562         //                                       .- send (3) commitment_signed
563         // (4) update_fee/commitment_signed      ->
564         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
565         //                                       <- (3) commitment_signed delivered
566         // send (6) revoke_and_ack               -.
567         //                                       <- (5) deliver revoke_and_ack
568         // (6) deliver revoke_and_ack            ->
569         //                                       .- send (7) commitment_signed in response to (4)
570         //                                       <- (7) deliver commitment_signed
571         // revoke_and_ack                        ->
572
573         // Create and deliver (1)...
574         let feerate = get_feerate!(nodes[0], channel_id);
575         nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
576         check_added_monitors!(nodes[0], 1);
577
578         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
579         assert_eq!(events_0.len(), 1);
580         let (update_msg, commitment_signed) = match events_0[0] {
581                         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 } } => {
582                         (update_fee.as_ref(), commitment_signed)
583                 },
584                 _ => panic!("Unexpected event"),
585         };
586         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
587
588         // Generate (2) and (3):
589         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
590         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
591         check_added_monitors!(nodes[1], 1);
592
593         // Deliver (2):
594         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
595         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
596         check_added_monitors!(nodes[0], 1);
597
598         // Create and deliver (4)...
599         nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
600         check_added_monitors!(nodes[0], 1);
601         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
602         assert_eq!(events_0.len(), 1);
603         let (update_msg, commitment_signed) = match events_0[0] {
604                         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 } } => {
605                         (update_fee.as_ref(), commitment_signed)
606                 },
607                 _ => panic!("Unexpected event"),
608         };
609
610         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
611         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
612         check_added_monitors!(nodes[1], 1);
613         // ... creating (5)
614         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
615         // No commitment_signed so get_event_msg's assert(len == 1) passes
616
617         // Handle (3), creating (6):
618         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0).unwrap();
619         check_added_monitors!(nodes[0], 1);
620         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
621         // No commitment_signed so get_event_msg's assert(len == 1) passes
622
623         // Deliver (5):
624         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
625         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
626         check_added_monitors!(nodes[0], 1);
627
628         // Deliver (6), creating (7):
629         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0).unwrap();
630         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
631         assert!(commitment_update.update_add_htlcs.is_empty());
632         assert!(commitment_update.update_fulfill_htlcs.is_empty());
633         assert!(commitment_update.update_fail_htlcs.is_empty());
634         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
635         assert!(commitment_update.update_fee.is_none());
636         check_added_monitors!(nodes[1], 1);
637
638         // Deliver (7)
639         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
640         check_added_monitors!(nodes[0], 1);
641         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
642         // No commitment_signed so get_event_msg's assert(len == 1) passes
643
644         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
645         check_added_monitors!(nodes[1], 1);
646         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
647
648         assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
649         assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
650         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
651 }
652
653 #[test]
654 fn pre_funding_lock_shutdown_test() {
655         // Test sending a shutdown prior to funding_locked after funding generation
656         let nodes = create_network(2, &[None, None]);
657         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0, LocalFeatures::new(), LocalFeatures::new());
658         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
659         nodes[0].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
660         nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
661
662         nodes[0].node.close_channel(&OutPoint::new(tx.txid(), 0).to_channel_id()).unwrap();
663         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
664         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
665         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
666         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
667
668         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
669         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
670         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
671         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
672         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
673         assert!(node_0_none.is_none());
674
675         assert!(nodes[0].node.list_channels().is_empty());
676         assert!(nodes[1].node.list_channels().is_empty());
677 }
678
679 #[test]
680 fn updates_shutdown_wait() {
681         // Test sending a shutdown with outstanding updates pending
682         let mut nodes = create_network(3, &[None, None, None]);
683         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
684         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
685         let route_1 = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
686         let route_2 = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
687
688         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
689
690         nodes[0].node.close_channel(&chan_1.2).unwrap();
691         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
692         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
693         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
694         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
695
696         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
697         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
698
699         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
700         if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route_1, payment_hash) {}
701         else { panic!("New sends should fail!") };
702         if let Err(APIError::ChannelUnavailable {..}) = nodes[1].node.send_payment(route_2, payment_hash) {}
703         else { panic!("New sends should fail!") };
704
705         assert!(nodes[2].node.claim_funds(our_payment_preimage));
706         check_added_monitors!(nodes[2], 1);
707         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
708         assert!(updates.update_add_htlcs.is_empty());
709         assert!(updates.update_fail_htlcs.is_empty());
710         assert!(updates.update_fail_malformed_htlcs.is_empty());
711         assert!(updates.update_fee.is_none());
712         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
713         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
714         check_added_monitors!(nodes[1], 1);
715         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
716         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
717
718         assert!(updates_2.update_add_htlcs.is_empty());
719         assert!(updates_2.update_fail_htlcs.is_empty());
720         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
721         assert!(updates_2.update_fee.is_none());
722         assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
723         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
724         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
725
726         let events = nodes[0].node.get_and_clear_pending_events();
727         assert_eq!(events.len(), 1);
728         match events[0] {
729                 Event::PaymentSent { ref payment_preimage } => {
730                         assert_eq!(our_payment_preimage, *payment_preimage);
731                 },
732                 _ => panic!("Unexpected event"),
733         }
734
735         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
736         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
737         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
738         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
739         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
740         assert!(node_0_none.is_none());
741
742         assert!(nodes[0].node.list_channels().is_empty());
743
744         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
745         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
746         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
747         assert!(nodes[1].node.list_channels().is_empty());
748         assert!(nodes[2].node.list_channels().is_empty());
749 }
750
751 #[test]
752 fn htlc_fail_async_shutdown() {
753         // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
754         let mut nodes = create_network(3, &[None, None, None]);
755         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
756         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
757
758         let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
759         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
760         nodes[0].node.send_payment(route, our_payment_hash).unwrap();
761         check_added_monitors!(nodes[0], 1);
762         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
763         assert_eq!(updates.update_add_htlcs.len(), 1);
764         assert!(updates.update_fulfill_htlcs.is_empty());
765         assert!(updates.update_fail_htlcs.is_empty());
766         assert!(updates.update_fail_malformed_htlcs.is_empty());
767         assert!(updates.update_fee.is_none());
768
769         nodes[1].node.close_channel(&chan_1.2).unwrap();
770         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
771         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
772         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
773
774         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
775         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed).unwrap();
776         check_added_monitors!(nodes[1], 1);
777         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
778         commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
779
780         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
781         assert!(updates_2.update_add_htlcs.is_empty());
782         assert!(updates_2.update_fulfill_htlcs.is_empty());
783         assert_eq!(updates_2.update_fail_htlcs.len(), 1);
784         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
785         assert!(updates_2.update_fee.is_none());
786
787         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]).unwrap();
788         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
789
790         let events = nodes[0].node.get_and_clear_pending_events();
791         assert_eq!(events.len(), 1);
792         match events[0] {
793                 Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } => {
794                         assert_eq!(our_payment_hash, *payment_hash);
795                         assert!(!rejected_by_dest);
796                 },
797                 _ => panic!("Unexpected event"),
798         }
799
800         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
801         assert_eq!(msg_events.len(), 2);
802         let node_0_closing_signed = match msg_events[0] {
803                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
804                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
805                         (*msg).clone()
806                 },
807                 _ => panic!("Unexpected event"),
808         };
809         match msg_events[1] {
810                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
811                         assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
812                 },
813                 _ => panic!("Unexpected event"),
814         }
815
816         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
817         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
818         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
819         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
820         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
821         assert!(node_0_none.is_none());
822
823         assert!(nodes[0].node.list_channels().is_empty());
824
825         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
826         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
827         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
828         assert!(nodes[1].node.list_channels().is_empty());
829         assert!(nodes[2].node.list_channels().is_empty());
830 }
831
832 fn do_test_shutdown_rebroadcast(recv_count: u8) {
833         // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
834         // messages delivered prior to disconnect
835         let nodes = create_network(3, &[None, None, None]);
836         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
837         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
838
839         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
840
841         nodes[1].node.close_channel(&chan_1.2).unwrap();
842         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
843         if recv_count > 0 {
844                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
845                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
846                 if recv_count > 1 {
847                         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
848                 }
849         }
850
851         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
852         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
853
854         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
855         let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
856         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
857         let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
858
859         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish).unwrap();
860         let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
861         assert!(node_1_shutdown == node_1_2nd_shutdown);
862
863         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish).unwrap();
864         let node_0_2nd_shutdown = if recv_count > 0 {
865                 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
866                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
867                 node_0_2nd_shutdown
868         } else {
869                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
870                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
871                 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
872         };
873         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown).unwrap();
874
875         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
876         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
877
878         assert!(nodes[2].node.claim_funds(our_payment_preimage));
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]).unwrap();
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]).unwrap();
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         if recv_count > 0 {
910                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
911                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
912                 assert!(node_1_closing_signed.is_some());
913         }
914
915         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
916         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
917
918         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
919         let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
920         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
921         if recv_count == 0 {
922                 // If all closing_signeds weren't delivered we can just resume where we left off...
923                 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
924
925                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish).unwrap();
926                 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
927                 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
928
929                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish).unwrap();
930                 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
931                 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
932
933                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown).unwrap();
934                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
935
936                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown).unwrap();
937                 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
938                 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
939
940                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed).unwrap();
941                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
942                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
943                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
944                 assert!(node_0_none.is_none());
945         } else {
946                 // If one node, however, received + responded with an identical closing_signed we end
947                 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
948                 // There isn't really anything better we can do simply, but in the future we might
949                 // explore storing a set of recently-closed channels that got disconnected during
950                 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
951                 // give our counterparty enough time to (potentially) broadcast a cooperative closing
952                 // transaction.
953                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
954
955                 if let Err(msgs::HandleError{action: Some(msgs::ErrorAction::SendErrorMessage{msg}), ..}) =
956                                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish) {
957                         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
958                         let msgs::ErrorMessage {ref channel_id, ..} = msg;
959                         assert_eq!(*channel_id, chan_1.2);
960                 } else { panic!("Needed SendErrorMessage close"); }
961
962                 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
963                 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
964                 // closing_signed so we do it ourselves
965                 check_closed_broadcast!(nodes[0]);
966         }
967
968         assert!(nodes[0].node.list_channels().is_empty());
969
970         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
971         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
972         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
973         assert!(nodes[1].node.list_channels().is_empty());
974         assert!(nodes[2].node.list_channels().is_empty());
975 }
976
977 #[test]
978 fn test_shutdown_rebroadcast() {
979         do_test_shutdown_rebroadcast(0);
980         do_test_shutdown_rebroadcast(1);
981         do_test_shutdown_rebroadcast(2);
982 }
983
984 #[test]
985 fn fake_network_test() {
986         // Simple test which builds a network of ChannelManagers, connects them to each other, and
987         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
988         let nodes = create_network(4, &[None, None, None, None]);
989
990         // Create some initial channels
991         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
992         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
993         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, LocalFeatures::new(), LocalFeatures::new());
994
995         // Rebalance the network a bit by relaying one payment through all the channels...
996         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
997         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
998         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
999         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1000
1001         // Send some more payments
1002         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
1003         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
1004         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
1005
1006         // Test failure packets
1007         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1008         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1009
1010         // Add a new channel that skips 3
1011         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, LocalFeatures::new(), LocalFeatures::new());
1012
1013         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1014         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
1015         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1016         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1017         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1018         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1019         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1020
1021         // Do some rebalance loop payments, simultaneously
1022         let mut hops = Vec::with_capacity(3);
1023         hops.push(RouteHop {
1024                 pubkey: nodes[2].node.get_our_node_id(),
1025                 short_channel_id: chan_2.0.contents.short_channel_id,
1026                 fee_msat: 0,
1027                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1028         });
1029         hops.push(RouteHop {
1030                 pubkey: nodes[3].node.get_our_node_id(),
1031                 short_channel_id: chan_3.0.contents.short_channel_id,
1032                 fee_msat: 0,
1033                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1034         });
1035         hops.push(RouteHop {
1036                 pubkey: nodes[1].node.get_our_node_id(),
1037                 short_channel_id: chan_4.0.contents.short_channel_id,
1038                 fee_msat: 1000000,
1039                 cltv_expiry_delta: TEST_FINAL_CLTV,
1040         });
1041         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;
1042         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;
1043         let payment_preimage_1 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1044
1045         let mut hops = Vec::with_capacity(3);
1046         hops.push(RouteHop {
1047                 pubkey: nodes[3].node.get_our_node_id(),
1048                 short_channel_id: chan_4.0.contents.short_channel_id,
1049                 fee_msat: 0,
1050                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1051         });
1052         hops.push(RouteHop {
1053                 pubkey: nodes[2].node.get_our_node_id(),
1054                 short_channel_id: chan_3.0.contents.short_channel_id,
1055                 fee_msat: 0,
1056                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1057         });
1058         hops.push(RouteHop {
1059                 pubkey: nodes[1].node.get_our_node_id(),
1060                 short_channel_id: chan_2.0.contents.short_channel_id,
1061                 fee_msat: 1000000,
1062                 cltv_expiry_delta: TEST_FINAL_CLTV,
1063         });
1064         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;
1065         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;
1066         let payment_hash_2 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1067
1068         // Claim the rebalances...
1069         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1070         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1071
1072         // Add a duplicate new channel from 2 to 4
1073         let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, LocalFeatures::new(), LocalFeatures::new());
1074
1075         // Send some payments across both channels
1076         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1077         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1078         let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1079
1080         route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1081
1082         //TODO: Test that routes work again here as we've been notified that the channel is full
1083
1084         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
1085         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
1086         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
1087
1088         // Close down the channels...
1089         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1090         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1091         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1092         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1093         close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1094 }
1095
1096 #[test]
1097 fn holding_cell_htlc_counting() {
1098         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1099         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1100         // commitment dance rounds.
1101         let mut nodes = create_network(3, &[None, None, None]);
1102         create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
1103         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
1104
1105         let mut payments = Vec::new();
1106         for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1107                 let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
1108                 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1109                 nodes[1].node.send_payment(route, payment_hash).unwrap();
1110                 payments.push((payment_preimage, payment_hash));
1111         }
1112         check_added_monitors!(nodes[1], 1);
1113
1114         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1115         assert_eq!(events.len(), 1);
1116         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1117         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1118
1119         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1120         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1121         // another HTLC.
1122         let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
1123         let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
1124         if let APIError::ChannelUnavailable { err } = nodes[1].node.send_payment(route, payment_hash_1).unwrap_err() {
1125                 assert_eq!(err, "Cannot push more than their max accepted HTLCs");
1126         } else { panic!("Unexpected event"); }
1127
1128         // This should also be true if we try to forward a payment.
1129         let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
1130         let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
1131         nodes[0].node.send_payment(route, payment_hash_2).unwrap();
1132         check_added_monitors!(nodes[0], 1);
1133
1134         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1135         assert_eq!(events.len(), 1);
1136         let payment_event = SendEvent::from_event(events.pop().unwrap());
1137         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1138
1139         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
1140         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1141         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1142         // fails), the second will process the resulting failure and fail the HTLC backward.
1143         expect_pending_htlcs_forwardable!(nodes[1]);
1144         expect_pending_htlcs_forwardable!(nodes[1]);
1145         check_added_monitors!(nodes[1], 1);
1146
1147         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1148         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]).unwrap();
1149         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1150
1151         let events = nodes[0].node.get_and_clear_pending_msg_events();
1152         assert_eq!(events.len(), 1);
1153         match events[0] {
1154                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
1155                         assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
1156                 },
1157                 _ => panic!("Unexpected event"),
1158         }
1159
1160         let events = nodes[0].node.get_and_clear_pending_events();
1161         assert_eq!(events.len(), 1);
1162         match events[0] {
1163                 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
1164                         assert_eq!(payment_hash, payment_hash_2);
1165                         assert!(!rejected_by_dest);
1166                 },
1167                 _ => panic!("Unexpected event"),
1168         }
1169
1170         // Now forward all the pending HTLCs and claim them back
1171         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]).unwrap();
1172         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg).unwrap();
1173         check_added_monitors!(nodes[2], 1);
1174
1175         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1176         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
1177         check_added_monitors!(nodes[1], 1);
1178         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1179
1180         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed).unwrap();
1181         check_added_monitors!(nodes[1], 1);
1182         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1183
1184         for ref update in as_updates.update_add_htlcs.iter() {
1185                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update).unwrap();
1186         }
1187         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed).unwrap();
1188         check_added_monitors!(nodes[2], 1);
1189         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
1190         check_added_monitors!(nodes[2], 1);
1191         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1192
1193         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
1194         check_added_monitors!(nodes[1], 1);
1195         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed).unwrap();
1196         check_added_monitors!(nodes[1], 1);
1197         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1198
1199         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa).unwrap();
1200         check_added_monitors!(nodes[2], 1);
1201
1202         expect_pending_htlcs_forwardable!(nodes[2]);
1203
1204         let events = nodes[2].node.get_and_clear_pending_events();
1205         assert_eq!(events.len(), payments.len());
1206         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1207                 match event {
1208                         &Event::PaymentReceived { ref payment_hash, .. } => {
1209                                 assert_eq!(*payment_hash, *hash);
1210                         },
1211                         _ => panic!("Unexpected event"),
1212                 };
1213         }
1214
1215         for (preimage, _) in payments.drain(..) {
1216                 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1217         }
1218
1219         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1220 }
1221
1222 #[test]
1223 fn duplicate_htlc_test() {
1224         // Test that we accept duplicate payment_hash HTLCs across the network and that
1225         // claiming/failing them are all separate and don't affect each other
1226         let mut nodes = create_network(6, &[None, None, None, None, None, None]);
1227
1228         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1229         create_announced_chan_between_nodes(&nodes, 0, 3, LocalFeatures::new(), LocalFeatures::new());
1230         create_announced_chan_between_nodes(&nodes, 1, 3, LocalFeatures::new(), LocalFeatures::new());
1231         create_announced_chan_between_nodes(&nodes, 2, 3, LocalFeatures::new(), LocalFeatures::new());
1232         create_announced_chan_between_nodes(&nodes, 3, 4, LocalFeatures::new(), LocalFeatures::new());
1233         create_announced_chan_between_nodes(&nodes, 3, 5, LocalFeatures::new(), LocalFeatures::new());
1234
1235         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1236
1237         *nodes[0].network_payment_count.borrow_mut() -= 1;
1238         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1239
1240         *nodes[0].network_payment_count.borrow_mut() -= 1;
1241         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1242
1243         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1244         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1245         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1246 }
1247
1248 fn do_channel_reserve_test(test_recv: bool) {
1249         use std::sync::atomic::Ordering;
1250         use ln::msgs::HandleError;
1251
1252         let mut nodes = create_network(3, &[None, None, None]);
1253         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1900, 1001, LocalFeatures::new(), LocalFeatures::new());
1254         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1900, 1001, LocalFeatures::new(), LocalFeatures::new());
1255
1256         let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1257         let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1258
1259         let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1260         let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1261
1262         macro_rules! get_route_and_payment_hash {
1263                 ($recv_value: expr) => {{
1264                         let route = nodes[0].router.get_route(&nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV).unwrap();
1265                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1266                         (route, payment_hash, payment_preimage)
1267                 }}
1268         };
1269
1270         macro_rules! expect_forward {
1271                 ($node: expr) => {{
1272                         let mut events = $node.node.get_and_clear_pending_msg_events();
1273                         assert_eq!(events.len(), 1);
1274                         check_added_monitors!($node, 1);
1275                         let payment_event = SendEvent::from_event(events.remove(0));
1276                         payment_event
1277                 }}
1278         }
1279
1280         let feemsat = 239; // somehow we know?
1281         let total_fee_msat = (nodes.len() - 2) as u64 * 239;
1282
1283         let recv_value_0 = stat01.their_max_htlc_value_in_flight_msat - total_fee_msat;
1284
1285         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1286         {
1287                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
1288                 assert!(route.hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1289                 let err = nodes[0].node.send_payment(route, our_payment_hash).err().unwrap();
1290                 match err {
1291                         APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over the max HTLC value in flight our peer will accept"),
1292                         _ => panic!("Unknown error variants"),
1293                 }
1294         }
1295
1296         let mut htlc_id = 0;
1297         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1298         // nodes[0]'s wealth
1299         loop {
1300                 let amt_msat = recv_value_0 + total_fee_msat;
1301                 if stat01.value_to_self_msat - amt_msat < stat01.channel_reserve_msat {
1302                         break;
1303                 }
1304                 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
1305                 htlc_id += 1;
1306
1307                 let (stat01_, stat11_, stat12_, stat22_) = (
1308                         get_channel_value_stat!(nodes[0], chan_1.2),
1309                         get_channel_value_stat!(nodes[1], chan_1.2),
1310                         get_channel_value_stat!(nodes[1], chan_2.2),
1311                         get_channel_value_stat!(nodes[2], chan_2.2),
1312                 );
1313
1314                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1315                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1316                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1317                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1318                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1319         }
1320
1321         {
1322                 let recv_value = stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat;
1323                 // attempt to get channel_reserve violation
1324                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value + 1);
1325                 let err = nodes[0].node.send_payment(route.clone(), our_payment_hash).err().unwrap();
1326                 match err {
1327                         APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over their reserve value"),
1328                         _ => panic!("Unknown error variants"),
1329                 }
1330         }
1331
1332         // adding pending output
1333         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat)/2;
1334         let amt_msat_1 = recv_value_1 + total_fee_msat;
1335
1336         let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
1337         let payment_event_1 = {
1338                 nodes[0].node.send_payment(route_1, our_payment_hash_1).unwrap();
1339                 check_added_monitors!(nodes[0], 1);
1340
1341                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1342                 assert_eq!(events.len(), 1);
1343                 SendEvent::from_event(events.remove(0))
1344         };
1345         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]).unwrap();
1346
1347         // channel reserve test with htlc pending output > 0
1348         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat;
1349         {
1350                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
1351                 match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
1352                         APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over their reserve value"),
1353                         _ => panic!("Unknown error variants"),
1354                 }
1355         }
1356
1357         {
1358                 // test channel_reserve test on nodes[1] side
1359                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
1360
1361                 // Need to manually create update_add_htlc message to go around the channel reserve check in send_htlc()
1362                 let secp_ctx = Secp256k1::new();
1363                 let session_priv = SecretKey::from_slice(&{
1364                         let mut session_key = [0; 32];
1365                         let mut rng = thread_rng();
1366                         rng.fill_bytes(&mut session_key);
1367                         session_key
1368                 }).expect("RNG is bad!");
1369
1370                 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1371                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
1372                 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
1373                 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, &our_payment_hash);
1374                 let msg = msgs::UpdateAddHTLC {
1375                         channel_id: chan_1.2,
1376                         htlc_id,
1377                         amount_msat: htlc_msat,
1378                         payment_hash: our_payment_hash,
1379                         cltv_expiry: htlc_cltv,
1380                         onion_routing_packet: onion_packet,
1381                 };
1382
1383                 if test_recv {
1384                         let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg).err().unwrap();
1385                         match err {
1386                                 HandleError{err, .. } => assert_eq!(err, "Remote HTLC add would put them over their reserve value"),
1387                         }
1388                         // If we send a garbage message, the channel should get closed, making the rest of this test case fail.
1389                         assert_eq!(nodes[1].node.list_channels().len(), 1);
1390                         assert_eq!(nodes[1].node.list_channels().len(), 1);
1391                         check_closed_broadcast!(nodes[1]);
1392                         return;
1393                 }
1394         }
1395
1396         // split the rest to test holding cell
1397         let recv_value_21 = recv_value_2/2;
1398         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat;
1399         {
1400                 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1401                 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), stat.channel_reserve_msat);
1402         }
1403
1404         // now see if they go through on both sides
1405         let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
1406         // but this will stuck in the holding cell
1407         nodes[0].node.send_payment(route_21, our_payment_hash_21).unwrap();
1408         check_added_monitors!(nodes[0], 0);
1409         let events = nodes[0].node.get_and_clear_pending_events();
1410         assert_eq!(events.len(), 0);
1411
1412         // test with outbound holding cell amount > 0
1413         {
1414                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
1415                 match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
1416                         APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over their reserve value"),
1417                         _ => panic!("Unknown error variants"),
1418                 }
1419         }
1420
1421         let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
1422         // this will also stuck in the holding cell
1423         nodes[0].node.send_payment(route_22, our_payment_hash_22).unwrap();
1424         check_added_monitors!(nodes[0], 0);
1425         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1426         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1427
1428         // flush the pending htlc
1429         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg).unwrap();
1430         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1431         check_added_monitors!(nodes[1], 1);
1432
1433         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
1434         check_added_monitors!(nodes[0], 1);
1435         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1436
1437         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed).unwrap();
1438         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1439         // No commitment_signed so get_event_msg's assert(len == 1) passes
1440         check_added_monitors!(nodes[0], 1);
1441
1442         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
1443         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1444         check_added_monitors!(nodes[1], 1);
1445
1446         expect_pending_htlcs_forwardable!(nodes[1]);
1447
1448         let ref payment_event_11 = expect_forward!(nodes[1]);
1449         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]).unwrap();
1450         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1451
1452         expect_pending_htlcs_forwardable!(nodes[2]);
1453         expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
1454
1455         // flush the htlcs in the holding cell
1456         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1457         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]).unwrap();
1458         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]).unwrap();
1459         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1460         expect_pending_htlcs_forwardable!(nodes[1]);
1461
1462         let ref payment_event_3 = expect_forward!(nodes[1]);
1463         assert_eq!(payment_event_3.msgs.len(), 2);
1464         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]).unwrap();
1465         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]).unwrap();
1466
1467         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1468         expect_pending_htlcs_forwardable!(nodes[2]);
1469
1470         let events = nodes[2].node.get_and_clear_pending_events();
1471         assert_eq!(events.len(), 2);
1472         match events[0] {
1473                 Event::PaymentReceived { ref payment_hash, amt } => {
1474                         assert_eq!(our_payment_hash_21, *payment_hash);
1475                         assert_eq!(recv_value_21, amt);
1476                 },
1477                 _ => panic!("Unexpected event"),
1478         }
1479         match events[1] {
1480                 Event::PaymentReceived { ref payment_hash, amt } => {
1481                         assert_eq!(our_payment_hash_22, *payment_hash);
1482                         assert_eq!(recv_value_22, amt);
1483                 },
1484                 _ => panic!("Unexpected event"),
1485         }
1486
1487         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
1488         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
1489         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
1490
1491         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);
1492         let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
1493         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
1494         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat);
1495
1496         let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
1497         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22);
1498 }
1499
1500 #[test]
1501 fn channel_reserve_test() {
1502         do_channel_reserve_test(false);
1503         do_channel_reserve_test(true);
1504 }
1505
1506 #[test]
1507 fn channel_reserve_in_flight_removes() {
1508         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
1509         // can send to its counterparty, but due to update ordering, the other side may not yet have
1510         // considered those HTLCs fully removed.
1511         // This tests that we don't count HTLCs which will not be included in the next remote
1512         // commitment transaction towards the reserve value (as it implies no commitment transaction
1513         // will be generated which violates the remote reserve value).
1514         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
1515         // To test this we:
1516         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
1517         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
1518         //    you only consider the value of the first HTLC, it may not),
1519         //  * start routing a third HTLC from A to B,
1520         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
1521         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
1522         //  * deliver the first fulfill from B
1523         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
1524         //    claim,
1525         //  * deliver A's response CS and RAA.
1526         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
1527         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
1528         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
1529         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
1530         let mut nodes = create_network(2, &[None, None]);
1531         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
1532
1533         let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
1534         // Route the first two HTLCs.
1535         let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
1536         let (payment_preimage_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
1537
1538         // Start routing the third HTLC (this is just used to get everyone in the right state).
1539         let (payment_preimage_3, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
1540         let send_1 = {
1541                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
1542                 nodes[0].node.send_payment(route, payment_hash_3).unwrap();
1543                 check_added_monitors!(nodes[0], 1);
1544                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1545                 assert_eq!(events.len(), 1);
1546                 SendEvent::from_event(events.remove(0))
1547         };
1548
1549         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
1550         // initial fulfill/CS.
1551         assert!(nodes[1].node.claim_funds(payment_preimage_1));
1552         check_added_monitors!(nodes[1], 1);
1553         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1554
1555         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
1556         // remove the second HTLC when we send the HTLC back from B to A.
1557         assert!(nodes[1].node.claim_funds(payment_preimage_2));
1558         check_added_monitors!(nodes[1], 1);
1559         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1560
1561         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]).unwrap();
1562         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed).unwrap();
1563         check_added_monitors!(nodes[0], 1);
1564         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1565         expect_payment_sent!(nodes[0], payment_preimage_1);
1566
1567         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]).unwrap();
1568         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg).unwrap();
1569         check_added_monitors!(nodes[1], 1);
1570         // B is already AwaitingRAA, so cant generate a CS here
1571         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1572
1573         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa).unwrap();
1574         check_added_monitors!(nodes[1], 1);
1575         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1576
1577         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa).unwrap();
1578         check_added_monitors!(nodes[0], 1);
1579         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1580
1581         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed).unwrap();
1582         check_added_monitors!(nodes[1], 1);
1583         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1584
1585         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
1586         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
1587         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
1588         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
1589         // on-chain as necessary).
1590         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]).unwrap();
1591         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed).unwrap();
1592         check_added_monitors!(nodes[0], 1);
1593         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1594         expect_payment_sent!(nodes[0], payment_preimage_2);
1595
1596         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa).unwrap();
1597         check_added_monitors!(nodes[1], 1);
1598         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1599
1600         expect_pending_htlcs_forwardable!(nodes[1]);
1601         expect_payment_received!(nodes[1], payment_hash_3, 100000);
1602
1603         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
1604         // resolve the second HTLC from A's point of view.
1605         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa).unwrap();
1606         check_added_monitors!(nodes[0], 1);
1607         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1608
1609         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
1610         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
1611         let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[1]);
1612         let send_2 = {
1613                 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &[], 10000, TEST_FINAL_CLTV).unwrap();
1614                 nodes[1].node.send_payment(route, payment_hash_4).unwrap();
1615                 check_added_monitors!(nodes[1], 1);
1616                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1617                 assert_eq!(events.len(), 1);
1618                 SendEvent::from_event(events.remove(0))
1619         };
1620
1621         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]).unwrap();
1622         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg).unwrap();
1623         check_added_monitors!(nodes[0], 1);
1624         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1625
1626         // Now just resolve all the outstanding messages/HTLCs for completeness...
1627
1628         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed).unwrap();
1629         check_added_monitors!(nodes[1], 1);
1630         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1631
1632         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa).unwrap();
1633         check_added_monitors!(nodes[1], 1);
1634
1635         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa).unwrap();
1636         check_added_monitors!(nodes[0], 1);
1637         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1638
1639         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed).unwrap();
1640         check_added_monitors!(nodes[1], 1);
1641         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1642
1643         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa).unwrap();
1644         check_added_monitors!(nodes[0], 1);
1645
1646         expect_pending_htlcs_forwardable!(nodes[0]);
1647         expect_payment_received!(nodes[0], payment_hash_4, 10000);
1648
1649         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
1650         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
1651 }
1652
1653 #[test]
1654 fn channel_monitor_network_test() {
1655         // Simple test which builds a network of ChannelManagers, connects them to each other, and
1656         // tests that ChannelMonitor is able to recover from various states.
1657         let nodes = create_network(5, &[None, None, None, None, None]);
1658
1659         // Create some initial channels
1660         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
1661         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
1662         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, LocalFeatures::new(), LocalFeatures::new());
1663         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, LocalFeatures::new(), LocalFeatures::new());
1664
1665         // Rebalance the network a bit by relaying one payment through all the channels...
1666         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
1667         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
1668         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
1669         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
1670
1671         // Simple case with no pending HTLCs:
1672         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
1673         {
1674                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
1675                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1676                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
1677                 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
1678         }
1679         get_announce_close_broadcast_events(&nodes, 0, 1);
1680         assert_eq!(nodes[0].node.list_channels().len(), 0);
1681         assert_eq!(nodes[1].node.list_channels().len(), 1);
1682
1683         // One pending HTLC is discarded by the force-close:
1684         let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
1685
1686         // Simple case of one pending HTLC to HTLC-Timeout
1687         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
1688         {
1689                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
1690                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1691                 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
1692                 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
1693         }
1694         get_announce_close_broadcast_events(&nodes, 1, 2);
1695         assert_eq!(nodes[1].node.list_channels().len(), 0);
1696         assert_eq!(nodes[2].node.list_channels().len(), 1);
1697
1698         macro_rules! claim_funds {
1699                 ($node: expr, $prev_node: expr, $preimage: expr) => {
1700                         {
1701                                 assert!($node.node.claim_funds($preimage));
1702                                 check_added_monitors!($node, 1);
1703
1704                                 let events = $node.node.get_and_clear_pending_msg_events();
1705                                 assert_eq!(events.len(), 1);
1706                                 match events[0] {
1707                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
1708                                                 assert!(update_add_htlcs.is_empty());
1709                                                 assert!(update_fail_htlcs.is_empty());
1710                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
1711                                         },
1712                                         _ => panic!("Unexpected event"),
1713                                 };
1714                         }
1715                 }
1716         }
1717
1718         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
1719         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
1720         nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
1721         {
1722                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
1723
1724                 // Claim the payment on nodes[3], giving it knowledge of the preimage
1725                 claim_funds!(nodes[3], nodes[2], payment_preimage_1);
1726
1727                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1728                 nodes[3].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
1729
1730                 check_preimage_claim(&nodes[3], &node_txn);
1731         }
1732         get_announce_close_broadcast_events(&nodes, 2, 3);
1733         assert_eq!(nodes[2].node.list_channels().len(), 0);
1734         assert_eq!(nodes[3].node.list_channels().len(), 1);
1735
1736         { // Cheat and reset nodes[4]'s height to 1
1737                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1738                 nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![] }, 1);
1739         }
1740
1741         assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
1742         assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
1743         // One pending HTLC to time out:
1744         let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
1745         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
1746         // buffer space).
1747
1748         {
1749                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1750                 nodes[3].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
1751                 for i in 3..TEST_FINAL_CLTV + 2 + LATENCY_GRACE_PERIOD_BLOCKS + 1 {
1752                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1753                         nodes[3].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
1754                 }
1755
1756                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
1757
1758                 // Claim the payment on nodes[4], giving it knowledge of the preimage
1759                 claim_funds!(nodes[4], nodes[3], payment_preimage_2);
1760
1761                 header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1762                 nodes[4].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
1763                 for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
1764                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1765                         nodes[4].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
1766                 }
1767
1768                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
1769
1770                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1771                 nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, TEST_FINAL_CLTV - 5);
1772
1773                 check_preimage_claim(&nodes[4], &node_txn);
1774         }
1775         get_announce_close_broadcast_events(&nodes, 3, 4);
1776         assert_eq!(nodes[3].node.list_channels().len(), 0);
1777         assert_eq!(nodes[4].node.list_channels().len(), 0);
1778 }
1779
1780 #[test]
1781 fn test_justice_tx() {
1782         // Test justice txn built on revoked HTLC-Success tx, against both sides
1783
1784         let mut alice_config = UserConfig::new();
1785         alice_config.channel_options.announced_channel = true;
1786         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
1787         alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
1788         let mut bob_config = UserConfig::new();
1789         bob_config.channel_options.announced_channel = true;
1790         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
1791         bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
1792         let nodes = create_network(2, &[Some(alice_config), Some(bob_config)]);
1793         // Create some new channels:
1794         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
1795
1796         // A pending HTLC which will be revoked:
1797         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
1798         // Get the will-be-revoked local txn from nodes[0]
1799         let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
1800         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
1801         assert_eq!(revoked_local_txn[0].input.len(), 1);
1802         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
1803         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
1804         assert_eq!(revoked_local_txn[1].input.len(), 1);
1805         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
1806         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
1807         // Revoke the old state
1808         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
1809
1810         {
1811                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1812                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
1813                 {
1814                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
1815                         assert_eq!(node_txn.len(), 3);
1816                         assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
1817                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
1818
1819                         check_spends!(node_txn[0], revoked_local_txn[0].clone());
1820                         node_txn.swap_remove(0);
1821                 }
1822                 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
1823
1824                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
1825                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
1826                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1827                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
1828                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone());
1829         }
1830         get_announce_close_broadcast_events(&nodes, 0, 1);
1831
1832         assert_eq!(nodes[0].node.list_channels().len(), 0);
1833         assert_eq!(nodes[1].node.list_channels().len(), 0);
1834
1835         // We test justice_tx build by A on B's revoked HTLC-Success tx
1836         // Create some new channels:
1837         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
1838
1839         // A pending HTLC which will be revoked:
1840         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
1841         // Get the will-be-revoked local txn from B
1842         let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
1843         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
1844         assert_eq!(revoked_local_txn[0].input.len(), 1);
1845         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
1846         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
1847         // Revoke the old state
1848         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
1849         {
1850                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1851                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
1852                 {
1853                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
1854                         assert_eq!(node_txn.len(), 3);
1855                         assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
1856                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
1857
1858                         check_spends!(node_txn[0], revoked_local_txn[0].clone());
1859                         node_txn.swap_remove(0);
1860                 }
1861                 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
1862
1863                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
1864                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
1865                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1866                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
1867                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone());
1868         }
1869         get_announce_close_broadcast_events(&nodes, 0, 1);
1870         assert_eq!(nodes[0].node.list_channels().len(), 0);
1871         assert_eq!(nodes[1].node.list_channels().len(), 0);
1872 }
1873
1874 #[test]
1875 fn revoked_output_claim() {
1876         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
1877         // transaction is broadcast by its counterparty
1878         let nodes = create_network(2, &[None, None]);
1879         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
1880         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
1881         let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
1882         assert_eq!(revoked_local_txn.len(), 1);
1883         // Only output is the full channel value back to nodes[0]:
1884         assert_eq!(revoked_local_txn[0].output.len(), 1);
1885         // Send a payment through, updating everyone's latest commitment txn
1886         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
1887
1888         // Inform nodes[1] that nodes[0] broadcast a stale tx
1889         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1890         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
1891         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
1892         assert_eq!(node_txn.len(), 3); // nodes[1] will broadcast justice tx twice, and its own local state once
1893
1894         assert_eq!(node_txn[0], node_txn[2]);
1895
1896         check_spends!(node_txn[0], revoked_local_txn[0].clone());
1897         check_spends!(node_txn[1], chan_1.3.clone());
1898
1899         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
1900         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
1901         get_announce_close_broadcast_events(&nodes, 0, 1);
1902 }
1903
1904 #[test]
1905 fn claim_htlc_outputs_shared_tx() {
1906         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
1907         let nodes = create_network(2, &[None, None]);
1908
1909         // Create some new channel:
1910         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
1911
1912         // Rebalance the network to generate htlc in the two directions
1913         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1914         // 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
1915         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
1916         let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
1917
1918         // Get the will-be-revoked local txn from node[0]
1919         let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
1920         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
1921         assert_eq!(revoked_local_txn[0].input.len(), 1);
1922         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
1923         assert_eq!(revoked_local_txn[1].input.len(), 1);
1924         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
1925         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
1926         check_spends!(revoked_local_txn[1], revoked_local_txn[0].clone());
1927
1928         //Revoke the old state
1929         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
1930
1931         {
1932                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1933                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
1934                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
1935                 connect_blocks(&nodes[1].chain_monitor, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
1936
1937                 let events = nodes[1].node.get_and_clear_pending_events();
1938                 assert_eq!(events.len(), 1);
1939                 match events[0] {
1940                         Event::PaymentFailed { payment_hash, .. } => {
1941                                 assert_eq!(payment_hash, payment_hash_2);
1942                         },
1943                         _ => panic!("Unexpected event"),
1944                 }
1945
1946                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
1947                 assert_eq!(node_txn.len(), 4);
1948
1949                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
1950                 check_spends!(node_txn[0], revoked_local_txn[0].clone());
1951
1952                 assert_eq!(node_txn[0], node_txn[3]); // justice tx is duplicated due to block re-scanning
1953
1954                 let mut witness_lens = BTreeSet::new();
1955                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
1956                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
1957                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
1958                 assert_eq!(witness_lens.len(), 3);
1959                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
1960                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
1961                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
1962
1963                 // Next nodes[1] broadcasts its current local tx state:
1964                 assert_eq!(node_txn[1].input.len(), 1);
1965                 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
1966
1967                 assert_eq!(node_txn[2].input.len(), 1);
1968                 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
1969                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
1970                 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
1971                 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
1972                 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
1973         }
1974         get_announce_close_broadcast_events(&nodes, 0, 1);
1975         assert_eq!(nodes[0].node.list_channels().len(), 0);
1976         assert_eq!(nodes[1].node.list_channels().len(), 0);
1977 }
1978
1979 #[test]
1980 fn claim_htlc_outputs_single_tx() {
1981         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
1982         let nodes = create_network(2, &[None, None]);
1983
1984         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
1985
1986         // Rebalance the network to generate htlc in the two directions
1987         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1988         // 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
1989         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
1990         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
1991         let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
1992
1993         // Get the will-be-revoked local txn from node[0]
1994         let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
1995
1996         //Revoke the old state
1997         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
1998
1999         {
2000                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2001                 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2002                 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2003                 connect_blocks(&nodes[1].chain_monitor, ANTI_REORG_DELAY - 1, 200, true, header.bitcoin_hash());
2004
2005                 let events = nodes[1].node.get_and_clear_pending_events();
2006                 assert_eq!(events.len(), 1);
2007                 match events[0] {
2008                         Event::PaymentFailed { payment_hash, .. } => {
2009                                 assert_eq!(payment_hash, payment_hash_2);
2010                         },
2011                         _ => panic!("Unexpected event"),
2012                 }
2013
2014                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2015                 assert_eq!(node_txn.len(), 22); // ChannelManager : 2, ChannelMontitor: 8 (1 standard revoked output, 2 revocation htlc tx, 1 local commitment tx + 1 htlc timeout tx) * 2 (block-rescan) + 5 * (1 local commitment tx + 1 htlc timeout tx)
2016
2017                 assert_eq!(node_txn[0], node_txn[7]);
2018                 assert_eq!(node_txn[1], node_txn[8]);
2019                 assert_eq!(node_txn[2], node_txn[9]);
2020                 assert_eq!(node_txn[3], node_txn[10]);
2021                 assert_eq!(node_txn[4], node_txn[11]);
2022                 assert_eq!(node_txn[3], node_txn[5]); //local commitment tx + htlc timeout tx broadcasted by ChannelManger
2023                 assert_eq!(node_txn[4], node_txn[6]);
2024
2025                 for i in 12..22 {
2026                         if i % 2 == 0 { assert_eq!(node_txn[3], node_txn[i]); } else { assert_eq!(node_txn[4], node_txn[i]); }
2027                 }
2028
2029                 assert_eq!(node_txn[0].input.len(), 1);
2030                 assert_eq!(node_txn[1].input.len(), 1);
2031                 assert_eq!(node_txn[2].input.len(), 1);
2032
2033                 let mut revoked_tx_map = HashMap::new();
2034                 revoked_tx_map.insert(revoked_local_txn[0].txid(), revoked_local_txn[0].clone());
2035                 node_txn[0].verify(&revoked_tx_map).unwrap();
2036                 node_txn[1].verify(&revoked_tx_map).unwrap();
2037                 node_txn[2].verify(&revoked_tx_map).unwrap();
2038
2039                 let mut witness_lens = BTreeSet::new();
2040                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2041                 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2042                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2043                 assert_eq!(witness_lens.len(), 3);
2044                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2045                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2046                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2047
2048                 assert_eq!(node_txn[3].input.len(), 1);
2049                 check_spends!(node_txn[3], chan_1.3.clone());
2050
2051                 assert_eq!(node_txn[4].input.len(), 1);
2052                 let witness_script = node_txn[4].input[0].witness.last().unwrap();
2053                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2054                 assert_eq!(node_txn[4].input[0].previous_output.txid, node_txn[3].txid());
2055                 assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
2056                 assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[1].input[0].previous_output.txid);
2057         }
2058         get_announce_close_broadcast_events(&nodes, 0, 1);
2059         assert_eq!(nodes[0].node.list_channels().len(), 0);
2060         assert_eq!(nodes[1].node.list_channels().len(), 0);
2061 }
2062
2063 #[test]
2064 fn test_htlc_on_chain_success() {
2065         // Test that in case of a unilateral close onchain, we detect the state of output thanks to
2066         // ChainWatchInterface and pass the preimage backward accordingly. So here we test that ChannelManager is
2067         // broadcasting the right event to other nodes in payment path.
2068         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2069         // A --------------------> B ----------------------> C (preimage)
2070         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2071         // commitment transaction was broadcast.
2072         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2073         // towards B.
2074         // B should be able to claim via preimage if A then broadcasts its local tx.
2075         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2076         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2077         // PaymentSent event).
2078
2079         let nodes = create_network(3, &[None, None, None]);
2080
2081         // Create some initial channels
2082         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
2083         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
2084
2085         // Rebalance the network a bit by relaying one payment through all the channels...
2086         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2087         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2088
2089         let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2090         let (our_payment_preimage_2, _payment_hash_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2091         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2092
2093         // Broadcast legit commitment tx from C on B's chain
2094         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2095         let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
2096         assert_eq!(commitment_tx.len(), 1);
2097         check_spends!(commitment_tx[0], chan_2.3.clone());
2098         nodes[2].node.claim_funds(our_payment_preimage);
2099         nodes[2].node.claim_funds(our_payment_preimage_2);
2100         check_added_monitors!(nodes[2], 2);
2101         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2102         assert!(updates.update_add_htlcs.is_empty());
2103         assert!(updates.update_fail_htlcs.is_empty());
2104         assert!(updates.update_fail_malformed_htlcs.is_empty());
2105         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2106
2107         nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2108         check_closed_broadcast!(nodes[2]);
2109         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx), ChannelMonitor : 4 (2*2 * HTLC-Success tx)
2110         assert_eq!(node_txn.len(), 5);
2111         assert_eq!(node_txn[0], node_txn[3]);
2112         assert_eq!(node_txn[1], node_txn[4]);
2113         assert_eq!(node_txn[2], commitment_tx[0]);
2114         check_spends!(node_txn[0], commitment_tx[0].clone());
2115         check_spends!(node_txn[1], commitment_tx[0].clone());
2116         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2117         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2118         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2119         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2120         assert_eq!(node_txn[0].lock_time, 0);
2121         assert_eq!(node_txn[1].lock_time, 0);
2122
2123         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2124         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: node_txn}, 1);
2125         let events = nodes[1].node.get_and_clear_pending_msg_events();
2126         {
2127                 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
2128                 assert_eq!(added_monitors.len(), 2);
2129                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2130                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2131                 added_monitors.clear();
2132         }
2133         assert_eq!(events.len(), 2);
2134         match events[0] {
2135                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2136                 _ => panic!("Unexpected event"),
2137         }
2138         match events[1] {
2139                 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, .. } } => {
2140                         assert!(update_add_htlcs.is_empty());
2141                         assert!(update_fail_htlcs.is_empty());
2142                         assert_eq!(update_fulfill_htlcs.len(), 1);
2143                         assert!(update_fail_malformed_htlcs.is_empty());
2144                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2145                 },
2146                 _ => panic!("Unexpected event"),
2147         };
2148         macro_rules! check_tx_local_broadcast {
2149                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2150                         // ChannelManager : 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor : 2 (timeout tx) * 2 (block-rescan)
2151                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2152                         assert_eq!(node_txn.len(), 7);
2153                         assert_eq!(node_txn[0], node_txn[5]);
2154                         assert_eq!(node_txn[1], node_txn[6]);
2155                         check_spends!(node_txn[0], $commitment_tx.clone());
2156                         check_spends!(node_txn[1], $commitment_tx.clone());
2157                         assert_ne!(node_txn[0].lock_time, 0);
2158                         assert_ne!(node_txn[1].lock_time, 0);
2159                         if $htlc_offered {
2160                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2161                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2162                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2163                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2164                         } else {
2165                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2166                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2167                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2168                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2169                         }
2170                         check_spends!(node_txn[2], $chan_tx.clone());
2171                         check_spends!(node_txn[3], node_txn[2].clone());
2172                         check_spends!(node_txn[4], node_txn[2].clone());
2173                         assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), 71);
2174                         assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2175                         assert_eq!(node_txn[4].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2176                         assert!(node_txn[3].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2177                         assert!(node_txn[4].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2178                         assert_ne!(node_txn[3].lock_time, 0);
2179                         assert_ne!(node_txn[4].lock_time, 0);
2180                         node_txn.clear();
2181                 } }
2182         }
2183         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2184         // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2185         // timeout-claim of the output that nodes[2] just claimed via success.
2186         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2187
2188         // Broadcast legit commitment tx from A on B's chain
2189         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2190         let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
2191         check_spends!(commitment_tx[0], chan_1.3.clone());
2192         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2193         check_closed_broadcast!(nodes[1]);
2194         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx), ChannelMonitor : 1 (HTLC-Success) * 2 (block-rescan)
2195         assert_eq!(node_txn.len(), 3);
2196         assert_eq!(node_txn[0], node_txn[2]);
2197         check_spends!(node_txn[0], commitment_tx[0].clone());
2198         assert_eq!(node_txn[0].input.len(), 2);
2199         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2200         assert_eq!(node_txn[0].input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2201         assert_eq!(node_txn[0].lock_time, 0);
2202         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2203         check_spends!(node_txn[1], chan_1.3.clone());
2204         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
2205         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2206         // we already checked the same situation with A.
2207
2208         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2209         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
2210         check_closed_broadcast!(nodes[0]);
2211         let events = nodes[0].node.get_and_clear_pending_events();
2212         assert_eq!(events.len(), 2);
2213         let mut first_claimed = false;
2214         for event in events {
2215                 match event {
2216                         Event::PaymentSent { payment_preimage } => {
2217                                 if payment_preimage == our_payment_preimage {
2218                                         assert!(!first_claimed);
2219                                         first_claimed = true;
2220                                 } else {
2221                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2222                                 }
2223                         },
2224                         _ => panic!("Unexpected event"),
2225                 }
2226         }
2227         check_tx_local_broadcast!(nodes[0], true, commitment_tx[0], chan_1.3);
2228 }
2229
2230 #[test]
2231 fn test_htlc_on_chain_timeout() {
2232         // Test that in case of a unilateral close onchain, we detect the state of output thanks to
2233         // ChainWatchInterface and timeout the HTLC backward accordingly. So here we test that ChannelManager is
2234         // broadcasting the right event to other nodes in payment path.
2235         // A ------------------> B ----------------------> C (timeout)
2236         //    B's commitment tx                 C's commitment tx
2237         //            \                                  \
2238         //         B's HTLC timeout tx               B's timeout tx
2239
2240         let nodes = create_network(3, &[None, None, None]);
2241
2242         // Create some intial channels
2243         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
2244         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
2245
2246         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2247         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2248         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2249
2250         let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2251         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2252
2253         // Broadcast legit commitment tx from C on B's chain
2254         let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
2255         check_spends!(commitment_tx[0], chan_2.3.clone());
2256         nodes[2].node.fail_htlc_backwards(&payment_hash);
2257         check_added_monitors!(nodes[2], 0);
2258         expect_pending_htlcs_forwardable!(nodes[2]);
2259         check_added_monitors!(nodes[2], 1);
2260
2261         let events = nodes[2].node.get_and_clear_pending_msg_events();
2262         assert_eq!(events.len(), 1);
2263         match events[0] {
2264                 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, .. } } => {
2265                         assert!(update_add_htlcs.is_empty());
2266                         assert!(!update_fail_htlcs.is_empty());
2267                         assert!(update_fulfill_htlcs.is_empty());
2268                         assert!(update_fail_malformed_htlcs.is_empty());
2269                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2270                 },
2271                 _ => panic!("Unexpected event"),
2272         };
2273         nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2274         check_closed_broadcast!(nodes[2]);
2275         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2276         assert_eq!(node_txn.len(), 1);
2277         check_spends!(node_txn[0], chan_2.3.clone());
2278         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2279
2280         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2281         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2282         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
2283         let timeout_tx;
2284         {
2285                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2286                 assert_eq!(node_txn.len(), 8); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 6 (HTLC-Timeout tx, commitment tx, timeout tx) * 2 (block-rescan)
2287                 assert_eq!(node_txn[0], node_txn[5]);
2288                 assert_eq!(node_txn[1], node_txn[6]);
2289                 assert_eq!(node_txn[2], node_txn[7]);
2290                 check_spends!(node_txn[0], commitment_tx[0].clone());
2291                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2292                 check_spends!(node_txn[1], chan_2.3.clone());
2293                 check_spends!(node_txn[2], node_txn[1].clone());
2294                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
2295                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2296                 check_spends!(node_txn[3], chan_2.3.clone());
2297                 check_spends!(node_txn[4], node_txn[3].clone());
2298                 assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2299                 assert_eq!(node_txn[4].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2300                 timeout_tx = node_txn[0].clone();
2301                 node_txn.clear();
2302         }
2303
2304         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![timeout_tx]}, 1);
2305         connect_blocks(&nodes[1].chain_monitor, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2306         check_added_monitors!(nodes[1], 0);
2307         check_closed_broadcast!(nodes[1]);
2308
2309         expect_pending_htlcs_forwardable!(nodes[1]);
2310         check_added_monitors!(nodes[1], 1);
2311         let events = nodes[1].node.get_and_clear_pending_msg_events();
2312         assert_eq!(events.len(), 1);
2313         match events[0] {
2314                 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, .. } } => {
2315                         assert!(update_add_htlcs.is_empty());
2316                         assert!(!update_fail_htlcs.is_empty());
2317                         assert!(update_fulfill_htlcs.is_empty());
2318                         assert!(update_fail_malformed_htlcs.is_empty());
2319                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2320                 },
2321                 _ => panic!("Unexpected event"),
2322         };
2323         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
2324         assert_eq!(node_txn.len(), 0);
2325
2326         // Broadcast legit commitment tx from B on A's chain
2327         let commitment_tx = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
2328         check_spends!(commitment_tx[0], chan_1.3.clone());
2329
2330         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
2331         check_closed_broadcast!(nodes[0]);
2332         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (timeout tx) * 2 block-rescan
2333         assert_eq!(node_txn.len(), 4);
2334         assert_eq!(node_txn[0], node_txn[3]);
2335         check_spends!(node_txn[0], commitment_tx[0].clone());
2336         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2337         check_spends!(node_txn[1], chan_1.3.clone());
2338         check_spends!(node_txn[2], node_txn[1].clone());
2339         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
2340         assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2341 }
2342
2343 #[test]
2344 fn test_simple_commitment_revoked_fail_backward() {
2345         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
2346         // and fail backward accordingly.
2347
2348         let nodes = create_network(3, &[None, None, None]);
2349
2350         // Create some initial channels
2351         create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
2352         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
2353
2354         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2355         // Get the will-be-revoked local txn from nodes[2]
2356         let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
2357         // Revoke the old state
2358         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
2359
2360         route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2361
2362         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2363         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2364         connect_blocks(&nodes[1].chain_monitor, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2365         check_added_monitors!(nodes[1], 0);
2366         check_closed_broadcast!(nodes[1]);
2367
2368         expect_pending_htlcs_forwardable!(nodes[1]);
2369         check_added_monitors!(nodes[1], 1);
2370         let events = nodes[1].node.get_and_clear_pending_msg_events();
2371         assert_eq!(events.len(), 1);
2372         match events[0] {
2373                 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, .. } } => {
2374                         assert!(update_add_htlcs.is_empty());
2375                         assert_eq!(update_fail_htlcs.len(), 1);
2376                         assert!(update_fulfill_htlcs.is_empty());
2377                         assert!(update_fail_malformed_htlcs.is_empty());
2378                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2379
2380                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]).unwrap();
2381                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2382
2383                         let events = nodes[0].node.get_and_clear_pending_msg_events();
2384                         assert_eq!(events.len(), 1);
2385                         match events[0] {
2386                                 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
2387                                 _ => panic!("Unexpected event"),
2388                         }
2389                         let events = nodes[0].node.get_and_clear_pending_events();
2390                         assert_eq!(events.len(), 1);
2391                         match events[0] {
2392                                 Event::PaymentFailed { .. } => {},
2393                                 _ => panic!("Unexpected event"),
2394                         }
2395                 },
2396                 _ => panic!("Unexpected event"),
2397         }
2398 }
2399
2400 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
2401         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
2402         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
2403         // commitment transaction anymore.
2404         // To do this, we have the peer which will broadcast a revoked commitment transaction send
2405         // a number of update_fail/commitment_signed updates without ever sending the RAA in
2406         // response to our commitment_signed. This is somewhat misbehavior-y, though not
2407         // technically disallowed and we should probably handle it reasonably.
2408         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
2409         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
2410         // transactions:
2411         // * Once we move it out of our holding cell/add it, we will immediately include it in a
2412         //   commitment_signed (implying it will be in the latest remote commitment transaction).
2413         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
2414         //   and once they revoke the previous commitment transaction (allowing us to send a new
2415         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
2416         let mut nodes = create_network(3, &[None, None, None]);
2417
2418         // Create some initial channels
2419         create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
2420         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
2421
2422         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
2423         // Get the will-be-revoked local txn from nodes[2]
2424         let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
2425         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
2426         // Revoke the old state
2427         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
2428
2429         let value = if use_dust {
2430                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
2431                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
2432                 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().our_dust_limit_satoshis * 1000
2433         } else { 3000000 };
2434
2435         let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2436         let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2437         let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2438
2439         assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash));
2440         expect_pending_htlcs_forwardable!(nodes[2]);
2441         check_added_monitors!(nodes[2], 1);
2442         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2443         assert!(updates.update_add_htlcs.is_empty());
2444         assert!(updates.update_fulfill_htlcs.is_empty());
2445         assert!(updates.update_fail_malformed_htlcs.is_empty());
2446         assert_eq!(updates.update_fail_htlcs.len(), 1);
2447         assert!(updates.update_fee.is_none());
2448         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
2449         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
2450         // Drop the last RAA from 3 -> 2
2451
2452         assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash));
2453         expect_pending_htlcs_forwardable!(nodes[2]);
2454         check_added_monitors!(nodes[2], 1);
2455         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2456         assert!(updates.update_add_htlcs.is_empty());
2457         assert!(updates.update_fulfill_htlcs.is_empty());
2458         assert!(updates.update_fail_malformed_htlcs.is_empty());
2459         assert_eq!(updates.update_fail_htlcs.len(), 1);
2460         assert!(updates.update_fee.is_none());
2461         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
2462         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed).unwrap();
2463         check_added_monitors!(nodes[1], 1);
2464         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
2465         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2466         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
2467         check_added_monitors!(nodes[2], 1);
2468
2469         assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash));
2470         expect_pending_htlcs_forwardable!(nodes[2]);
2471         check_added_monitors!(nodes[2], 1);
2472         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2473         assert!(updates.update_add_htlcs.is_empty());
2474         assert!(updates.update_fulfill_htlcs.is_empty());
2475         assert!(updates.update_fail_malformed_htlcs.is_empty());
2476         assert_eq!(updates.update_fail_htlcs.len(), 1);
2477         assert!(updates.update_fee.is_none());
2478         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
2479         // At this point first_payment_hash has dropped out of the latest two commitment
2480         // transactions that nodes[1] is tracking...
2481         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed).unwrap();
2482         check_added_monitors!(nodes[1], 1);
2483         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
2484         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2485         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
2486         check_added_monitors!(nodes[2], 1);
2487
2488         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
2489         // on nodes[2]'s RAA.
2490         let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
2491         let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
2492         nodes[1].node.send_payment(route, fourth_payment_hash).unwrap();
2493         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2494         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2495         check_added_monitors!(nodes[1], 0);
2496
2497         if deliver_bs_raa {
2498                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa).unwrap();
2499                 // One monitor for the new revocation preimage, no second on as we won't generate a new
2500                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
2501                 check_added_monitors!(nodes[1], 1);
2502                 let events = nodes[1].node.get_and_clear_pending_events();
2503                 assert_eq!(events.len(), 1);
2504                 match events[0] {
2505                         Event::PendingHTLCsForwardable { .. } => { },
2506                         _ => panic!("Unexpected event"),
2507                 };
2508                 // Deliberately don't process the pending fail-back so they all fail back at once after
2509                 // block connection just like the !deliver_bs_raa case
2510         }
2511
2512         let mut failed_htlcs = HashSet::new();
2513         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2514
2515         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2516         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2517         connect_blocks(&nodes[1].chain_monitor, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2518
2519         let events = nodes[1].node.get_and_clear_pending_events();
2520         assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
2521         match events[0] {
2522                 Event::PaymentFailed { ref payment_hash, .. } => {
2523                         assert_eq!(*payment_hash, fourth_payment_hash);
2524                 },
2525                 _ => panic!("Unexpected event"),
2526         }
2527         if !deliver_bs_raa {
2528                 match events[1] {
2529                         Event::PendingHTLCsForwardable { .. } => { },
2530                         _ => panic!("Unexpected event"),
2531                 };
2532         }
2533         nodes[1].node.process_pending_htlc_forwards();
2534         check_added_monitors!(nodes[1], 1);
2535
2536         let events = nodes[1].node.get_and_clear_pending_msg_events();
2537         assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
2538         match events[if deliver_bs_raa { 1 } else { 0 }] {
2539                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
2540                 _ => panic!("Unexpected event"),
2541         }
2542         if deliver_bs_raa {
2543                 match events[0] {
2544                         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, .. } } => {
2545                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
2546                                 assert_eq!(update_add_htlcs.len(), 1);
2547                                 assert!(update_fulfill_htlcs.is_empty());
2548                                 assert!(update_fail_htlcs.is_empty());
2549                                 assert!(update_fail_malformed_htlcs.is_empty());
2550                         },
2551                         _ => panic!("Unexpected event"),
2552                 }
2553         }
2554         match events[if deliver_bs_raa { 2 } else { 1 }] {
2555                 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, .. } } => {
2556                         assert!(update_add_htlcs.is_empty());
2557                         assert_eq!(update_fail_htlcs.len(), 3);
2558                         assert!(update_fulfill_htlcs.is_empty());
2559                         assert!(update_fail_malformed_htlcs.is_empty());
2560                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2561
2562                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]).unwrap();
2563                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]).unwrap();
2564                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]).unwrap();
2565
2566                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2567
2568                         let events = nodes[0].node.get_and_clear_pending_msg_events();
2569                         // If we delivered B's RAA we got an unknown preimage error, not something
2570                         // that we should update our routing table for.
2571                         assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
2572                         for event in events {
2573                                 match event {
2574                                         MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
2575                                         _ => panic!("Unexpected event"),
2576                                 }
2577                         }
2578                         let events = nodes[0].node.get_and_clear_pending_events();
2579                         assert_eq!(events.len(), 3);
2580                         match events[0] {
2581                                 Event::PaymentFailed { ref payment_hash, .. } => {
2582                                         assert!(failed_htlcs.insert(payment_hash.0));
2583                                 },
2584                                 _ => panic!("Unexpected event"),
2585                         }
2586                         match events[1] {
2587                                 Event::PaymentFailed { ref payment_hash, .. } => {
2588                                         assert!(failed_htlcs.insert(payment_hash.0));
2589                                 },
2590                                 _ => panic!("Unexpected event"),
2591                         }
2592                         match events[2] {
2593                                 Event::PaymentFailed { ref payment_hash, .. } => {
2594                                         assert!(failed_htlcs.insert(payment_hash.0));
2595                                 },
2596                                 _ => panic!("Unexpected event"),
2597                         }
2598                 },
2599                 _ => panic!("Unexpected event"),
2600         }
2601
2602         assert!(failed_htlcs.contains(&first_payment_hash.0));
2603         assert!(failed_htlcs.contains(&second_payment_hash.0));
2604         assert!(failed_htlcs.contains(&third_payment_hash.0));
2605 }
2606
2607 #[test]
2608 fn test_commitment_revoked_fail_backward_exhaustive_a() {
2609         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
2610         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
2611         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
2612         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
2613 }
2614
2615 #[test]
2616 fn test_commitment_revoked_fail_backward_exhaustive_b() {
2617         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
2618         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
2619         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
2620         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
2621 }
2622
2623 #[test]
2624 fn test_htlc_ignore_latest_remote_commitment() {
2625         // Test that HTLC transactions spending the latest remote commitment transaction are simply
2626         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
2627         let nodes = create_network(2, &[None, None]);
2628         create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
2629
2630         route_payment(&nodes[0], &[&nodes[1]], 10000000);
2631         nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
2632         check_closed_broadcast!(nodes[0]);
2633
2634         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2635         assert_eq!(node_txn.len(), 2);
2636
2637         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2638         nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
2639         check_closed_broadcast!(nodes[1]);
2640
2641         // Duplicate the block_connected call since this may happen due to other listeners
2642         // registering new transactions
2643         nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
2644 }
2645
2646 #[test]
2647 fn test_force_close_fail_back() {
2648         // Check which HTLCs are failed-backwards on channel force-closure
2649         let mut nodes = create_network(3, &[None, None, None]);
2650         create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
2651         create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
2652
2653         let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, 42).unwrap();
2654
2655         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
2656
2657         let mut payment_event = {
2658                 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
2659                 check_added_monitors!(nodes[0], 1);
2660
2661                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2662                 assert_eq!(events.len(), 1);
2663                 SendEvent::from_event(events.remove(0))
2664         };
2665
2666         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
2667         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
2668
2669         expect_pending_htlcs_forwardable!(nodes[1]);
2670
2671         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
2672         assert_eq!(events_2.len(), 1);
2673         payment_event = SendEvent::from_event(events_2.remove(0));
2674         assert_eq!(payment_event.msgs.len(), 1);
2675
2676         check_added_monitors!(nodes[1], 1);
2677         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
2678         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
2679         check_added_monitors!(nodes[2], 1);
2680         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2681
2682         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
2683         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
2684         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
2685
2686         nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
2687         check_closed_broadcast!(nodes[2]);
2688         let tx = {
2689                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
2690                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
2691                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
2692                 // back to nodes[1] upon timeout otherwise.
2693                 assert_eq!(node_txn.len(), 1);
2694                 node_txn.remove(0)
2695         };
2696
2697         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2698         nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
2699
2700         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
2701         check_closed_broadcast!(nodes[1]);
2702
2703         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
2704         {
2705                 let mut monitors = nodes[2].chan_monitor.simple_monitor.monitors.lock().unwrap();
2706                 monitors.get_mut(&OutPoint::new(Sha256dHash::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), 0)).unwrap()
2707                         .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
2708         }
2709         nodes[2].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
2710         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
2711         assert_eq!(node_txn.len(), 1);
2712         assert_eq!(node_txn[0].input.len(), 1);
2713         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
2714         assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
2715         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
2716
2717         check_spends!(node_txn[0], tx);
2718 }
2719
2720 #[test]
2721 fn test_unconf_chan() {
2722         // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
2723         let nodes = create_network(2, &[None, None]);
2724         create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
2725
2726         let channel_state = nodes[0].node.channel_state.lock().unwrap();
2727         assert_eq!(channel_state.by_id.len(), 1);
2728         assert_eq!(channel_state.short_to_id.len(), 1);
2729         mem::drop(channel_state);
2730
2731         let mut headers = Vec::new();
2732         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2733         headers.push(header.clone());
2734         for _i in 2..100 {
2735                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2736                 headers.push(header.clone());
2737         }
2738         let mut height = 99;
2739         while !headers.is_empty() {
2740                 nodes[0].node.block_disconnected(&headers.pop().unwrap(), height);
2741                 height -= 1;
2742         }
2743         check_closed_broadcast!(nodes[0]);
2744         let channel_state = nodes[0].node.channel_state.lock().unwrap();
2745         assert_eq!(channel_state.by_id.len(), 0);
2746         assert_eq!(channel_state.short_to_id.len(), 0);
2747 }
2748
2749 #[test]
2750 fn test_simple_peer_disconnect() {
2751         // Test that we can reconnect when there are no lost messages
2752         let nodes = create_network(3, &[None, None, None]);
2753         create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
2754         create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
2755
2756         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
2757         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
2758         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
2759
2760         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
2761         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
2762         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
2763         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
2764
2765         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
2766         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
2767         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
2768
2769         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
2770         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
2771         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
2772         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
2773
2774         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
2775         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
2776
2777         claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3);
2778         fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
2779
2780         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
2781         {
2782                 let events = nodes[0].node.get_and_clear_pending_events();
2783                 assert_eq!(events.len(), 2);
2784                 match events[0] {
2785                         Event::PaymentSent { payment_preimage } => {
2786                                 assert_eq!(payment_preimage, payment_preimage_3);
2787                         },
2788                         _ => panic!("Unexpected event"),
2789                 }
2790                 match events[1] {
2791                         Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
2792                                 assert_eq!(payment_hash, payment_hash_5);
2793                                 assert!(rejected_by_dest);
2794                         },
2795                         _ => panic!("Unexpected event"),
2796                 }
2797         }
2798
2799         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
2800         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
2801 }
2802
2803 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
2804         // Test that we can reconnect when in-flight HTLC updates get dropped
2805         let mut nodes = create_network(2, &[None, None]);
2806         if messages_delivered == 0 {
2807                 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, LocalFeatures::new(), LocalFeatures::new());
2808                 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
2809         } else {
2810                 create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
2811         }
2812
2813         let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels()), &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
2814         let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
2815
2816         let payment_event = {
2817                 nodes[0].node.send_payment(route.clone(), payment_hash_1).unwrap();
2818                 check_added_monitors!(nodes[0], 1);
2819
2820                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2821                 assert_eq!(events.len(), 1);
2822                 SendEvent::from_event(events.remove(0))
2823         };
2824         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
2825
2826         if messages_delivered < 2 {
2827                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
2828         } else {
2829                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
2830                 if messages_delivered >= 3 {
2831                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
2832                         check_added_monitors!(nodes[1], 1);
2833                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2834
2835                         if messages_delivered >= 4 {
2836                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
2837                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2838                                 check_added_monitors!(nodes[0], 1);
2839
2840                                 if messages_delivered >= 5 {
2841                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
2842                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2843                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
2844                                         check_added_monitors!(nodes[0], 1);
2845
2846                                         if messages_delivered >= 6 {
2847                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
2848                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2849                                                 check_added_monitors!(nodes[1], 1);
2850                                         }
2851                                 }
2852                         }
2853                 }
2854         }
2855
2856         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
2857         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
2858         if messages_delivered < 3 {
2859                 // Even if the funding_locked messages get exchanged, as long as nothing further was
2860                 // received on either side, both sides will need to resend them.
2861                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
2862         } else if messages_delivered == 3 {
2863                 // nodes[0] still wants its RAA + commitment_signed
2864                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
2865         } else if messages_delivered == 4 {
2866                 // nodes[0] still wants its commitment_signed
2867                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
2868         } else if messages_delivered == 5 {
2869                 // nodes[1] still wants its final RAA
2870                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
2871         } else if messages_delivered == 6 {
2872                 // Everything was delivered...
2873                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
2874         }
2875
2876         let events_1 = nodes[1].node.get_and_clear_pending_events();
2877         assert_eq!(events_1.len(), 1);
2878         match events_1[0] {
2879                 Event::PendingHTLCsForwardable { .. } => { },
2880                 _ => panic!("Unexpected event"),
2881         };
2882
2883         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
2884         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
2885         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
2886
2887         nodes[1].node.process_pending_htlc_forwards();
2888
2889         let events_2 = nodes[1].node.get_and_clear_pending_events();
2890         assert_eq!(events_2.len(), 1);
2891         match events_2[0] {
2892                 Event::PaymentReceived { ref payment_hash, amt } => {
2893                         assert_eq!(payment_hash_1, *payment_hash);
2894                         assert_eq!(amt, 1000000);
2895                 },
2896                 _ => panic!("Unexpected event"),
2897         }
2898
2899         nodes[1].node.claim_funds(payment_preimage_1);
2900         check_added_monitors!(nodes[1], 1);
2901
2902         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
2903         assert_eq!(events_3.len(), 1);
2904         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
2905                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
2906                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
2907                         assert!(updates.update_add_htlcs.is_empty());
2908                         assert!(updates.update_fail_htlcs.is_empty());
2909                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2910                         assert!(updates.update_fail_malformed_htlcs.is_empty());
2911                         assert!(updates.update_fee.is_none());
2912                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
2913                 },
2914                 _ => panic!("Unexpected event"),
2915         };
2916
2917         if messages_delivered >= 1 {
2918                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc).unwrap();
2919
2920                 let events_4 = nodes[0].node.get_and_clear_pending_events();
2921                 assert_eq!(events_4.len(), 1);
2922                 match events_4[0] {
2923                         Event::PaymentSent { ref payment_preimage } => {
2924                                 assert_eq!(payment_preimage_1, *payment_preimage);
2925                         },
2926                         _ => panic!("Unexpected event"),
2927                 }
2928
2929                 if messages_delivered >= 2 {
2930                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
2931                         check_added_monitors!(nodes[0], 1);
2932                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2933
2934                         if messages_delivered >= 3 {
2935                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
2936                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2937                                 check_added_monitors!(nodes[1], 1);
2938
2939                                 if messages_delivered >= 4 {
2940                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed).unwrap();
2941                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2942                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
2943                                         check_added_monitors!(nodes[1], 1);
2944
2945                                         if messages_delivered >= 5 {
2946                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
2947                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2948                                                 check_added_monitors!(nodes[0], 1);
2949                                         }
2950                                 }
2951                         }
2952                 }
2953         }
2954
2955         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
2956         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
2957         if messages_delivered < 2 {
2958                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
2959                 //TODO: Deduplicate PaymentSent events, then enable this if:
2960                 //if messages_delivered < 1 {
2961                         let events_4 = nodes[0].node.get_and_clear_pending_events();
2962                         assert_eq!(events_4.len(), 1);
2963                         match events_4[0] {
2964                                 Event::PaymentSent { ref payment_preimage } => {
2965                                         assert_eq!(payment_preimage_1, *payment_preimage);
2966                                 },
2967                                 _ => panic!("Unexpected event"),
2968                         }
2969                 //}
2970         } else if messages_delivered == 2 {
2971                 // nodes[0] still wants its RAA + commitment_signed
2972                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
2973         } else if messages_delivered == 3 {
2974                 // nodes[0] still wants its commitment_signed
2975                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
2976         } else if messages_delivered == 4 {
2977                 // nodes[1] still wants its final RAA
2978                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
2979         } else if messages_delivered == 5 {
2980                 // Everything was delivered...
2981                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
2982         }
2983
2984         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
2985         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
2986         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
2987
2988         // Channel should still work fine...
2989         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
2990         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
2991 }
2992
2993 #[test]
2994 fn test_drop_messages_peer_disconnect_a() {
2995         do_test_drop_messages_peer_disconnect(0);
2996         do_test_drop_messages_peer_disconnect(1);
2997         do_test_drop_messages_peer_disconnect(2);
2998         do_test_drop_messages_peer_disconnect(3);
2999 }
3000
3001 #[test]
3002 fn test_drop_messages_peer_disconnect_b() {
3003         do_test_drop_messages_peer_disconnect(4);
3004         do_test_drop_messages_peer_disconnect(5);
3005         do_test_drop_messages_peer_disconnect(6);
3006 }
3007
3008 #[test]
3009 fn test_funding_peer_disconnect() {
3010         // Test that we can lock in our funding tx while disconnected
3011         let nodes = create_network(2, &[None, None]);
3012         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, LocalFeatures::new(), LocalFeatures::new());
3013
3014         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3015         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3016
3017         confirm_transaction(&nodes[0].chain_monitor, &tx, tx.version);
3018         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3019         assert_eq!(events_1.len(), 1);
3020         match events_1[0] {
3021                 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3022                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3023                 },
3024                 _ => panic!("Unexpected event"),
3025         }
3026
3027         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3028
3029         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3030         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3031
3032         confirm_transaction(&nodes[1].chain_monitor, &tx, tx.version);
3033         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3034         assert_eq!(events_2.len(), 2);
3035         match events_2[0] {
3036                 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3037                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3038                 },
3039                 _ => panic!("Unexpected event"),
3040         }
3041         match events_2[1] {
3042                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, msg: _ } => {
3043                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3044                 },
3045                 _ => panic!("Unexpected event"),
3046         }
3047
3048         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3049
3050         // TODO: We shouldn't need to manually pass list_usable_chanels here once we support
3051         // rebroadcasting announcement_signatures upon reconnect.
3052
3053         let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels()), &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
3054         let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3055         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
3056 }
3057
3058 #[test]
3059 fn test_drop_messages_peer_disconnect_dual_htlc() {
3060         // Test that we can handle reconnecting when both sides of a channel have pending
3061         // commitment_updates when we disconnect.
3062         let mut nodes = create_network(2, &[None, None]);
3063         create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
3064
3065         let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3066
3067         // Now try to send a second payment which will fail to send
3068         let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
3069         let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
3070
3071         nodes[0].node.send_payment(route.clone(), payment_hash_2).unwrap();
3072         check_added_monitors!(nodes[0], 1);
3073
3074         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3075         assert_eq!(events_1.len(), 1);
3076         match events_1[0] {
3077                 MessageSendEvent::UpdateHTLCs { .. } => {},
3078                 _ => panic!("Unexpected event"),
3079         }
3080
3081         assert!(nodes[1].node.claim_funds(payment_preimage_1));
3082         check_added_monitors!(nodes[1], 1);
3083
3084         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3085         assert_eq!(events_2.len(), 1);
3086         match events_2[0] {
3087                 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 } } => {
3088                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3089                         assert!(update_add_htlcs.is_empty());
3090                         assert_eq!(update_fulfill_htlcs.len(), 1);
3091                         assert!(update_fail_htlcs.is_empty());
3092                         assert!(update_fail_malformed_htlcs.is_empty());
3093                         assert!(update_fee.is_none());
3094
3095                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
3096                         let events_3 = nodes[0].node.get_and_clear_pending_events();
3097                         assert_eq!(events_3.len(), 1);
3098                         match events_3[0] {
3099                                 Event::PaymentSent { ref payment_preimage } => {
3100                                         assert_eq!(*payment_preimage, payment_preimage_1);
3101                                 },
3102                                 _ => panic!("Unexpected event"),
3103                         }
3104
3105                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
3106                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3107                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3108                         check_added_monitors!(nodes[0], 1);
3109                 },
3110                 _ => panic!("Unexpected event"),
3111         }
3112
3113         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3114         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3115
3116         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
3117         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3118         assert_eq!(reestablish_1.len(), 1);
3119         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
3120         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3121         assert_eq!(reestablish_2.len(), 1);
3122
3123         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
3124         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3125         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
3126         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3127
3128         assert!(as_resp.0.is_none());
3129         assert!(bs_resp.0.is_none());
3130
3131         assert!(bs_resp.1.is_none());
3132         assert!(bs_resp.2.is_none());
3133
3134         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3135
3136         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3137         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3138         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3139         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3140         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3141         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]).unwrap();
3142         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed).unwrap();
3143         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3144         // No commitment_signed so get_event_msg's assert(len == 1) passes
3145         check_added_monitors!(nodes[1], 1);
3146
3147         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap()).unwrap();
3148         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3149         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3150         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3151         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3152         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3153         assert!(bs_second_commitment_signed.update_fee.is_none());
3154         check_added_monitors!(nodes[1], 1);
3155
3156         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
3157         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3158         assert!(as_commitment_signed.update_add_htlcs.is_empty());
3159         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
3160         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
3161         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
3162         assert!(as_commitment_signed.update_fee.is_none());
3163         check_added_monitors!(nodes[0], 1);
3164
3165         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed).unwrap();
3166         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3167         // No commitment_signed so get_event_msg's assert(len == 1) passes
3168         check_added_monitors!(nodes[0], 1);
3169
3170         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed).unwrap();
3171         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3172         // No commitment_signed so get_event_msg's assert(len == 1) passes
3173         check_added_monitors!(nodes[1], 1);
3174
3175         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
3176         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3177         check_added_monitors!(nodes[1], 1);
3178
3179         expect_pending_htlcs_forwardable!(nodes[1]);
3180
3181         let events_5 = nodes[1].node.get_and_clear_pending_events();
3182         assert_eq!(events_5.len(), 1);
3183         match events_5[0] {
3184                 Event::PaymentReceived { ref payment_hash, amt: _ } => {
3185                         assert_eq!(payment_hash_2, *payment_hash);
3186                 },
3187                 _ => panic!("Unexpected event"),
3188         }
3189
3190         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap();
3191         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3192         check_added_monitors!(nodes[0], 1);
3193
3194         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3195 }
3196
3197 #[test]
3198 fn test_invalid_channel_announcement() {
3199         //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
3200         let secp_ctx = Secp256k1::new();
3201         let nodes = create_network(2, &[None, None]);
3202
3203         let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1], LocalFeatures::new(), LocalFeatures::new());
3204
3205         let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
3206         let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
3207         let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
3208         let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
3209
3210         let _ = nodes[0].router.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id : as_chan.get_short_channel_id().unwrap(), is_permanent: false } );
3211
3212         let as_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &as_chan.get_local_keys().funding_key);
3213         let bs_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &bs_chan.get_local_keys().funding_key);
3214
3215         let as_network_key = nodes[0].node.get_our_node_id();
3216         let bs_network_key = nodes[1].node.get_our_node_id();
3217
3218         let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
3219
3220         let mut chan_announcement;
3221
3222         macro_rules! dummy_unsigned_msg {
3223                 () => {
3224                         msgs::UnsignedChannelAnnouncement {
3225                                 features: msgs::GlobalFeatures::new(),
3226                                 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
3227                                 short_channel_id: as_chan.get_short_channel_id().unwrap(),
3228                                 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
3229                                 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
3230                                 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
3231                                 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
3232                                 excess_data: Vec::new(),
3233                         };
3234                 }
3235         }
3236
3237         macro_rules! sign_msg {
3238                 ($unsigned_msg: expr) => {
3239                         let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
3240                         let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_local_keys().funding_key);
3241                         let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_local_keys().funding_key);
3242                         let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
3243                         let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
3244                         chan_announcement = msgs::ChannelAnnouncement {
3245                                 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
3246                                 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
3247                                 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
3248                                 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
3249                                 contents: $unsigned_msg
3250                         }
3251                 }
3252         }
3253
3254         let unsigned_msg = dummy_unsigned_msg!();
3255         sign_msg!(unsigned_msg);
3256         assert_eq!(nodes[0].router.handle_channel_announcement(&chan_announcement).unwrap(), true);
3257         let _ = nodes[0].router.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id : as_chan.get_short_channel_id().unwrap(), is_permanent: false } );
3258
3259         // Configured with Network::Testnet
3260         let mut unsigned_msg = dummy_unsigned_msg!();
3261         unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.bitcoin_hash();
3262         sign_msg!(unsigned_msg);
3263         assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
3264
3265         let mut unsigned_msg = dummy_unsigned_msg!();
3266         unsigned_msg.chain_hash = Sha256dHash::hash(&[1,2,3,4,5,6,7,8,9]);
3267         sign_msg!(unsigned_msg);
3268         assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
3269 }
3270
3271 #[test]
3272 fn test_no_txn_manager_serialize_deserialize() {
3273         let mut nodes = create_network(2, &[None, None]);
3274
3275         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, LocalFeatures::new(), LocalFeatures::new());
3276
3277         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3278
3279         let nodes_0_serialized = nodes[0].node.encode();
3280         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3281         nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
3282
3283         nodes[0].chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), Arc::new(test_utils::TestLogger::new()), Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 })));
3284         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3285         let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
3286         assert!(chan_0_monitor_read.is_empty());
3287
3288         let mut nodes_0_read = &nodes_0_serialized[..];
3289         let config = UserConfig::new();
3290         let keys_manager = Arc::new(test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
3291         let (_, nodes_0_deserialized) = {
3292                 let mut channel_monitors = HashMap::new();
3293                 channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
3294                 <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3295                         default_config: config,
3296                         keys_manager,
3297                         fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
3298                         monitor: nodes[0].chan_monitor.clone(),
3299                         chain_monitor: nodes[0].chain_monitor.clone(),
3300                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3301                         logger: Arc::new(test_utils::TestLogger::new()),
3302                         channel_monitors: &channel_monitors,
3303                 }).unwrap()
3304         };
3305         assert!(nodes_0_read.is_empty());
3306
3307         assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
3308         nodes[0].node = Arc::new(nodes_0_deserialized);
3309         let nodes_0_as_listener: Arc<ChainListener> = nodes[0].node.clone();
3310         nodes[0].chain_monitor.register_listener(Arc::downgrade(&nodes_0_as_listener));
3311         assert_eq!(nodes[0].node.list_channels().len(), 1);
3312         check_added_monitors!(nodes[0], 1);
3313
3314         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
3315         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3316         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
3317         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3318
3319         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
3320         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3321         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
3322         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3323
3324         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
3325         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
3326         for node in nodes.iter() {
3327                 assert!(node.router.handle_channel_announcement(&announcement).unwrap());
3328                 node.router.handle_channel_update(&as_update).unwrap();
3329                 node.router.handle_channel_update(&bs_update).unwrap();
3330         }
3331
3332         send_payment(&nodes[0], &[&nodes[1]], 1000000);
3333 }
3334
3335 #[test]
3336 fn test_simple_manager_serialize_deserialize() {
3337         let mut nodes = create_network(2, &[None, None]);
3338         create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
3339
3340         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3341         let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3342
3343         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3344
3345         let nodes_0_serialized = nodes[0].node.encode();
3346         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3347         nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
3348
3349         nodes[0].chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), Arc::new(test_utils::TestLogger::new()), Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 })));
3350         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3351         let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
3352         assert!(chan_0_monitor_read.is_empty());
3353
3354         let mut nodes_0_read = &nodes_0_serialized[..];
3355         let keys_manager = Arc::new(test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
3356         let (_, nodes_0_deserialized) = {
3357                 let mut channel_monitors = HashMap::new();
3358                 channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
3359                 <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3360                         default_config: UserConfig::new(),
3361                         keys_manager,
3362                         fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
3363                         monitor: nodes[0].chan_monitor.clone(),
3364                         chain_monitor: nodes[0].chain_monitor.clone(),
3365                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3366                         logger: Arc::new(test_utils::TestLogger::new()),
3367                         channel_monitors: &channel_monitors,
3368                 }).unwrap()
3369         };
3370         assert!(nodes_0_read.is_empty());
3371
3372         assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
3373         nodes[0].node = Arc::new(nodes_0_deserialized);
3374         check_added_monitors!(nodes[0], 1);
3375
3376         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3377
3378         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
3379         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
3380 }
3381
3382 #[test]
3383 fn test_manager_serialize_deserialize_inconsistent_monitor() {
3384         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
3385         let mut nodes = create_network(4, &[None, None, None, None]);
3386         create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
3387         create_announced_chan_between_nodes(&nodes, 2, 0, LocalFeatures::new(), LocalFeatures::new());
3388         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, LocalFeatures::new(), LocalFeatures::new());
3389
3390         let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
3391
3392         // Serialize the ChannelManager here, but the monitor we keep up-to-date
3393         let nodes_0_serialized = nodes[0].node.encode();
3394
3395         route_payment(&nodes[0], &[&nodes[3]], 1000000);
3396         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3397         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3398         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3399
3400         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
3401         // nodes[3])
3402         let mut node_0_monitors_serialized = Vec::new();
3403         for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
3404                 let mut writer = test_utils::TestVecWriter(Vec::new());
3405                 monitor.1.write_for_disk(&mut writer).unwrap();
3406                 node_0_monitors_serialized.push(writer.0);
3407         }
3408
3409         nodes[0].chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), Arc::new(test_utils::TestLogger::new()), Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 })));
3410         let mut node_0_monitors = Vec::new();
3411         for serialized in node_0_monitors_serialized.iter() {
3412                 let mut read = &serialized[..];
3413                 let (_, monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut read, Arc::new(test_utils::TestLogger::new())).unwrap();
3414                 assert!(read.is_empty());
3415                 node_0_monitors.push(monitor);
3416         }
3417
3418         let mut nodes_0_read = &nodes_0_serialized[..];
3419         let keys_manager = Arc::new(test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
3420         let (_, nodes_0_deserialized) = <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3421                 default_config: UserConfig::new(),
3422                 keys_manager,
3423                 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
3424                 monitor: nodes[0].chan_monitor.clone(),
3425                 chain_monitor: nodes[0].chain_monitor.clone(),
3426                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3427                 logger: Arc::new(test_utils::TestLogger::new()),
3428                 channel_monitors: &node_0_monitors.iter().map(|monitor| { (monitor.get_funding_txo().unwrap(), monitor) }).collect(),
3429         }).unwrap();
3430         assert!(nodes_0_read.is_empty());
3431
3432         { // Channel close should result in a commitment tx and an HTLC tx
3433                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3434                 assert_eq!(txn.len(), 2);
3435                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
3436                 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
3437         }
3438
3439         for monitor in node_0_monitors.drain(..) {
3440                 assert!(nodes[0].chan_monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor).is_ok());
3441                 check_added_monitors!(nodes[0], 1);
3442         }
3443         nodes[0].node = Arc::new(nodes_0_deserialized);
3444
3445         // nodes[1] and nodes[2] have no lost state with nodes[0]...
3446         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3447         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3448         //... and we can even still claim the payment!
3449         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
3450
3451         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id());
3452         let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
3453         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id());
3454         if let Err(msgs::HandleError { action: Some(msgs::ErrorAction::SendErrorMessage { msg }), .. }) = nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish) {
3455                 assert_eq!(msg.channel_id, channel_id);
3456         } else { panic!("Unexpected result"); }
3457 }
3458
3459 macro_rules! check_spendable_outputs {
3460         ($node: expr, $der_idx: expr) => {
3461                 {
3462                         let events = $node.chan_monitor.simple_monitor.get_and_clear_pending_events();
3463                         let mut txn = Vec::new();
3464                         for event in events {
3465                                 match event {
3466                                         Event::SpendableOutputs { ref outputs } => {
3467                                                 for outp in outputs {
3468                                                         match *outp {
3469                                                                 SpendableOutputDescriptor::DynamicOutputP2WPKH { ref outpoint, ref key, ref output } => {
3470                                                                         let input = TxIn {
3471                                                                                 previous_output: outpoint.clone(),
3472                                                                                 script_sig: Script::new(),
3473                                                                                 sequence: 0,
3474                                                                                 witness: Vec::new(),
3475                                                                         };
3476                                                                         let outp = TxOut {
3477                                                                                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
3478                                                                                 value: output.value,
3479                                                                         };
3480                                                                         let mut spend_tx = Transaction {
3481                                                                                 version: 2,
3482                                                                                 lock_time: 0,
3483                                                                                 input: vec![input],
3484                                                                                 output: vec![outp],
3485                                                                         };
3486                                                                         let secp_ctx = Secp256k1::new();
3487                                                                         let remotepubkey = PublicKey::from_secret_key(&secp_ctx, &key);
3488                                                                         let witness_script = Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: remotepubkey}, Network::Testnet).script_pubkey();
3489                                                                         let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
3490                                                                         let remotesig = secp_ctx.sign(&sighash, key);
3491                                                                         spend_tx.input[0].witness.push(remotesig.serialize_der().to_vec());
3492                                                                         spend_tx.input[0].witness[0].push(SigHashType::All as u8);
3493                                                                         spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
3494                                                                         txn.push(spend_tx);
3495                                                                 },
3496                                                                 SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref key, ref witness_script, ref to_self_delay, ref output } => {
3497                                                                         let input = TxIn {
3498                                                                                 previous_output: outpoint.clone(),
3499                                                                                 script_sig: Script::new(),
3500                                                                                 sequence: *to_self_delay as u32,
3501                                                                                 witness: Vec::new(),
3502                                                                         };
3503                                                                         let outp = TxOut {
3504                                                                                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
3505                                                                                 value: output.value,
3506                                                                         };
3507                                                                         let mut spend_tx = Transaction {
3508                                                                                 version: 2,
3509                                                                                 lock_time: 0,
3510                                                                                 input: vec![input],
3511                                                                                 output: vec![outp],
3512                                                                         };
3513                                                                         let secp_ctx = Secp256k1::new();
3514                                                                         let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], witness_script, output.value)[..]).unwrap();
3515                                                                         let local_delaysig = secp_ctx.sign(&sighash, key);
3516                                                                         spend_tx.input[0].witness.push(local_delaysig.serialize_der().to_vec());
3517                                                                         spend_tx.input[0].witness[0].push(SigHashType::All as u8);
3518                                                                         spend_tx.input[0].witness.push(vec!(0));
3519                                                                         spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
3520                                                                         txn.push(spend_tx);
3521                                                                 },
3522                                                                 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
3523                                                                         let secp_ctx = Secp256k1::new();
3524                                                                         let input = TxIn {
3525                                                                                 previous_output: outpoint.clone(),
3526                                                                                 script_sig: Script::new(),
3527                                                                                 sequence: 0,
3528                                                                                 witness: Vec::new(),
3529                                                                         };
3530                                                                         let outp = TxOut {
3531                                                                                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
3532                                                                                 value: output.value,
3533                                                                         };
3534                                                                         let mut spend_tx = Transaction {
3535                                                                                 version: 2,
3536                                                                                 lock_time: 0,
3537                                                                                 input: vec![input],
3538                                                                                 output: vec![outp.clone()],
3539                                                                         };
3540                                                                         let secret = {
3541                                                                                 match ExtendedPrivKey::new_master(Network::Testnet, &$node.node_seed) {
3542                                                                                         Ok(master_key) => {
3543                                                                                                 match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx).expect("key space exhausted")) {
3544                                                                                                         Ok(key) => key,
3545                                                                                                         Err(_) => panic!("Your RNG is busted"),
3546                                                                                                 }
3547                                                                                         }
3548                                                                                         Err(_) => panic!("Your rng is busted"),
3549                                                                                 }
3550                                                                         };
3551                                                                         let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
3552                                                                         let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
3553                                                                         let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
3554                                                                         let sig = secp_ctx.sign(&sighash, &secret.private_key.key);
3555                                                                         spend_tx.input[0].witness.push(sig.serialize_der().to_vec());
3556                                                                         spend_tx.input[0].witness[0].push(SigHashType::All as u8);
3557                                                                         spend_tx.input[0].witness.push(pubkey.key.serialize().to_vec());
3558                                                                         txn.push(spend_tx);
3559                                                                 },
3560                                                         }
3561                                                 }
3562                                         },
3563                                         _ => panic!("Unexpected event"),
3564                                 };
3565                         }
3566                         txn
3567                 }
3568         }
3569 }
3570
3571 #[test]
3572 fn test_claim_sizeable_push_msat() {
3573         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
3574         let nodes = create_network(2, &[None, None]);
3575
3576         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, LocalFeatures::new(), LocalFeatures::new());
3577         nodes[1].node.force_close_channel(&chan.2);
3578         check_closed_broadcast!(nodes[1]);
3579         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3580         assert_eq!(node_txn.len(), 1);
3581         check_spends!(node_txn[0], chan.3.clone());
3582         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
3583
3584         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3585         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
3586         let spend_txn = check_spendable_outputs!(nodes[1], 1);
3587         assert_eq!(spend_txn.len(), 1);
3588         check_spends!(spend_txn[0], node_txn[0].clone());
3589 }
3590
3591 #[test]
3592 fn test_claim_on_remote_sizeable_push_msat() {
3593         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
3594         // to_remote output is encumbered by a P2WPKH
3595
3596         let nodes = create_network(2, &[None, None]);
3597
3598         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, LocalFeatures::new(), LocalFeatures::new());
3599         nodes[0].node.force_close_channel(&chan.2);
3600         check_closed_broadcast!(nodes[0]);
3601
3602         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3603         assert_eq!(node_txn.len(), 1);
3604         check_spends!(node_txn[0], chan.3.clone());
3605         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
3606
3607         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3608         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
3609         check_closed_broadcast!(nodes[1]);
3610         let spend_txn = check_spendable_outputs!(nodes[1], 1);
3611         assert_eq!(spend_txn.len(), 2);
3612         assert_eq!(spend_txn[0], spend_txn[1]);
3613         check_spends!(spend_txn[0], node_txn[0].clone());
3614 }
3615
3616 #[test]
3617 fn test_claim_on_remote_revoked_sizeable_push_msat() {
3618         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
3619         // to_remote output is encumbered by a P2WPKH
3620
3621         let nodes = create_network(2, &[None, None]);
3622
3623         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, LocalFeatures::new(), LocalFeatures::new());
3624         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
3625         let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
3626         assert_eq!(revoked_local_txn[0].input.len(), 1);
3627         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
3628
3629         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
3630         let  header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3631         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3632         check_closed_broadcast!(nodes[1]);
3633
3634         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3635         let spend_txn = check_spendable_outputs!(nodes[1], 1);
3636         assert_eq!(spend_txn.len(), 4);
3637         assert_eq!(spend_txn[0], spend_txn[2]); // to_remote output on revoked remote commitment_tx
3638         check_spends!(spend_txn[0], revoked_local_txn[0].clone());
3639         assert_eq!(spend_txn[1], spend_txn[3]); // to_local output on local commitment tx
3640         check_spends!(spend_txn[1], node_txn[0].clone());
3641 }
3642
3643 #[test]
3644 fn test_static_spendable_outputs_preimage_tx() {
3645         let nodes = create_network(2, &[None, None]);
3646
3647         // Create some initial channels
3648         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
3649
3650         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
3651
3652         let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
3653         assert_eq!(commitment_tx[0].input.len(), 1);
3654         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
3655
3656         // Settle A's commitment tx on B's chain
3657         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3658         assert!(nodes[1].node.claim_funds(payment_preimage));
3659         check_added_monitors!(nodes[1], 1);
3660         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
3661         let events = nodes[1].node.get_and_clear_pending_msg_events();
3662         match events[0] {
3663                 MessageSendEvent::UpdateHTLCs { .. } => {},
3664                 _ => panic!("Unexpected event"),
3665         }
3666         match events[1] {
3667                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
3668                 _ => panic!("Unexepected event"),
3669         }
3670
3671         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
3672         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 1 (local commitment tx), ChannelMonitor: 2 (1 preimage tx) * 2 (block-rescan)
3673         check_spends!(node_txn[0], commitment_tx[0].clone());
3674         assert_eq!(node_txn[0], node_txn[2]);
3675         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3676         check_spends!(node_txn[1], chan_1.3.clone());
3677
3678         let spend_txn = check_spendable_outputs!(nodes[1], 1); // , 0, 0, 1, 1);
3679         assert_eq!(spend_txn.len(), 2);
3680         assert_eq!(spend_txn[0], spend_txn[1]);
3681         check_spends!(spend_txn[0], node_txn[0].clone());
3682 }
3683
3684 #[test]
3685 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
3686         let nodes = create_network(2, &[None, None]);
3687
3688         // Create some initial channels
3689         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
3690
3691         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
3692         let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
3693         assert_eq!(revoked_local_txn[0].input.len(), 1);
3694         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
3695
3696         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
3697
3698         let  header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3699         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3700         check_closed_broadcast!(nodes[1]);
3701
3702         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3703         assert_eq!(node_txn.len(), 3);
3704         assert_eq!(node_txn.pop().unwrap(), node_txn[0]);
3705         assert_eq!(node_txn[0].input.len(), 2);
3706         check_spends!(node_txn[0], revoked_local_txn[0].clone());
3707
3708         let spend_txn = check_spendable_outputs!(nodes[1], 1);
3709         assert_eq!(spend_txn.len(), 2);
3710         assert_eq!(spend_txn[0], spend_txn[1]);
3711         check_spends!(spend_txn[0], node_txn[0].clone());
3712 }
3713
3714 #[test]
3715 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
3716         let nodes = create_network(2, &[None, None]);
3717
3718         // Create some initial channels
3719         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
3720
3721         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
3722         let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
3723         assert_eq!(revoked_local_txn[0].input.len(), 1);
3724         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
3725
3726         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
3727
3728         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3729         // A will generate HTLC-Timeout from revoked commitment tx
3730         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3731         check_closed_broadcast!(nodes[0]);
3732
3733         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3734         assert_eq!(revoked_htlc_txn.len(), 3);
3735         assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
3736         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
3737         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3738         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
3739         check_spends!(revoked_htlc_txn[1], chan_1.3.clone());
3740
3741         // B will generate justice tx from A's revoked commitment/HTLC tx
3742         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
3743         check_closed_broadcast!(nodes[1]);
3744
3745         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3746         assert_eq!(node_txn.len(), 4);
3747         assert_eq!(node_txn[3].input.len(), 1);
3748         check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
3749
3750         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
3751         let spend_txn = check_spendable_outputs!(nodes[1], 1);
3752         assert_eq!(spend_txn.len(), 3);
3753         assert_eq!(spend_txn[0], spend_txn[1]);
3754         check_spends!(spend_txn[0], node_txn[0].clone());
3755         check_spends!(spend_txn[2], node_txn[3].clone());
3756 }
3757
3758 #[test]
3759 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
3760         let nodes = create_network(2, &[None, None]);
3761
3762         // Create some initial channels
3763         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
3764
3765         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
3766         let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
3767         assert_eq!(revoked_local_txn[0].input.len(), 1);
3768         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
3769
3770         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
3771
3772         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3773         // B will generate HTLC-Success from revoked commitment tx
3774         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3775         check_closed_broadcast!(nodes[1]);
3776         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3777
3778         assert_eq!(revoked_htlc_txn.len(), 3);
3779         assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
3780         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
3781         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3782         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
3783
3784         // A will generate justice tx from B's revoked commitment/HTLC tx
3785         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
3786         check_closed_broadcast!(nodes[0]);
3787
3788         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3789         assert_eq!(node_txn.len(), 4);
3790         assert_eq!(node_txn[3].input.len(), 1);
3791         check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
3792
3793         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
3794         let spend_txn = check_spendable_outputs!(nodes[0], 1);
3795         assert_eq!(spend_txn.len(), 5);
3796         assert_eq!(spend_txn[0], spend_txn[2]);
3797         assert_eq!(spend_txn[1], spend_txn[3]);
3798         check_spends!(spend_txn[0], revoked_local_txn[0].clone()); // spending to_remote output from revoked local tx
3799         check_spends!(spend_txn[1], node_txn[2].clone()); // spending justice tx output from revoked local tx htlc received output
3800         check_spends!(spend_txn[4], node_txn[3].clone()); // spending justice tx output on htlc success tx
3801 }
3802
3803 #[test]
3804 fn test_onchain_to_onchain_claim() {
3805         // Test that in case of channel closure, we detect the state of output thanks to
3806         // ChainWatchInterface and claim HTLC on downstream peer's remote commitment tx.
3807         // First, have C claim an HTLC against its own latest commitment transaction.
3808         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
3809         // channel.
3810         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
3811         // gets broadcast.
3812
3813         let nodes = create_network(3, &[None, None, None]);
3814
3815         // Create some initial channels
3816         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
3817         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
3818
3819         // Rebalance the network a bit by relaying one payment through all the channels ...
3820         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
3821         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
3822
3823         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
3824         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
3825         let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
3826         check_spends!(commitment_tx[0], chan_2.3.clone());
3827         nodes[2].node.claim_funds(payment_preimage);
3828         check_added_monitors!(nodes[2], 1);
3829         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3830         assert!(updates.update_add_htlcs.is_empty());
3831         assert!(updates.update_fail_htlcs.is_empty());
3832         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3833         assert!(updates.update_fail_malformed_htlcs.is_empty());
3834
3835         nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
3836         check_closed_broadcast!(nodes[2]);
3837
3838         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
3839         assert_eq!(c_txn.len(), 3);
3840         assert_eq!(c_txn[0], c_txn[2]);
3841         assert_eq!(commitment_tx[0], c_txn[1]);
3842         check_spends!(c_txn[1], chan_2.3.clone());
3843         check_spends!(c_txn[2], c_txn[1].clone());
3844         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
3845         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3846         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
3847         assert_eq!(c_txn[0].lock_time, 0); // Success tx
3848
3849         // 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
3850         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
3851         {
3852                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3853                 assert_eq!(b_txn.len(), 4);
3854                 assert_eq!(b_txn[0], b_txn[3]);
3855                 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
3856                 check_spends!(b_txn[2], b_txn[1].clone()); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
3857                 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3858                 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
3859                 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
3860                 check_spends!(b_txn[0], c_txn[1].clone()); // timeout tx on C remote commitment tx, issued by ChannelMonitor, * 2 due to block rescan
3861                 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3862                 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
3863                 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
3864                 b_txn.clear();
3865         }
3866         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
3867         check_added_monitors!(nodes[1], 1);
3868         match msg_events[0] {
3869                 MessageSendEvent::BroadcastChannelUpdate {  .. } => {},
3870                 _ => panic!("Unexpected event"),
3871         }
3872         match msg_events[1] {
3873                 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, .. } } => {
3874                         assert!(update_add_htlcs.is_empty());
3875                         assert!(update_fail_htlcs.is_empty());
3876                         assert_eq!(update_fulfill_htlcs.len(), 1);
3877                         assert!(update_fail_malformed_htlcs.is_empty());
3878                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3879                 },
3880                 _ => panic!("Unexpected event"),
3881         };
3882         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
3883         let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
3884         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
3885         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3886         assert_eq!(b_txn.len(), 3);
3887         check_spends!(b_txn[1], chan_1.3); // Local commitment tx, issued by ChannelManager
3888         assert_eq!(b_txn[0], b_txn[2]); // HTLC-Success tx, issued by ChannelMonitor, * 2 due to block rescan
3889         check_spends!(b_txn[0], commitment_tx[0].clone());
3890         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3891         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
3892         assert_eq!(b_txn[2].lock_time, 0); // Success tx
3893
3894         check_closed_broadcast!(nodes[1]);
3895 }
3896
3897 #[test]
3898 fn test_duplicate_payment_hash_one_failure_one_success() {
3899         // Topology : A --> B --> C
3900         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
3901         let mut nodes = create_network(3, &[None, None, None]);
3902
3903         create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
3904         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
3905
3906         let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
3907         *nodes[0].network_payment_count.borrow_mut() -= 1;
3908         assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
3909
3910         let commitment_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
3911         assert_eq!(commitment_txn[0].input.len(), 1);
3912         check_spends!(commitment_txn[0], chan_2.3.clone());
3913
3914         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3915         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
3916         check_closed_broadcast!(nodes[1]);
3917
3918         let htlc_timeout_tx;
3919         { // Extract one of the two HTLC-Timeout transaction
3920                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3921                 assert_eq!(node_txn.len(), 7);
3922                 assert_eq!(node_txn[0], node_txn[5]);
3923                 assert_eq!(node_txn[1], node_txn[6]);
3924                 check_spends!(node_txn[0], commitment_txn[0].clone());
3925                 assert_eq!(node_txn[0].input.len(), 1);
3926                 check_spends!(node_txn[1], commitment_txn[0].clone());
3927                 assert_eq!(node_txn[1].input.len(), 1);
3928                 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
3929                 check_spends!(node_txn[2], chan_2.3.clone());
3930                 check_spends!(node_txn[3], node_txn[2].clone());
3931                 check_spends!(node_txn[4], node_txn[2].clone());
3932                 htlc_timeout_tx = node_txn[1].clone();
3933         }
3934
3935         nodes[2].node.claim_funds(our_payment_preimage);
3936         nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
3937         check_added_monitors!(nodes[2], 2);
3938         let events = nodes[2].node.get_and_clear_pending_msg_events();
3939         match events[0] {
3940                 MessageSendEvent::UpdateHTLCs { .. } => {},
3941                 _ => panic!("Unexpected event"),
3942         }
3943         match events[1] {
3944                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
3945                 _ => panic!("Unexepected event"),
3946         }
3947         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
3948         assert_eq!(htlc_success_txn.len(), 5);
3949         check_spends!(htlc_success_txn[2], chan_2.3.clone());
3950         assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
3951         assert_eq!(htlc_success_txn[0].input.len(), 1);
3952         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3953         assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
3954         assert_eq!(htlc_success_txn[1].input.len(), 1);
3955         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3956         assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
3957         check_spends!(htlc_success_txn[0], commitment_txn[0].clone());
3958         check_spends!(htlc_success_txn[1], commitment_txn[0].clone());
3959
3960         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![htlc_timeout_tx] }, 200);
3961         connect_blocks(&nodes[1].chain_monitor, ANTI_REORG_DELAY - 1, 200, true, header.bitcoin_hash());
3962         expect_pending_htlcs_forwardable!(nodes[1]);
3963         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3964         assert!(htlc_updates.update_add_htlcs.is_empty());
3965         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
3966         assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
3967         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
3968         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
3969         check_added_monitors!(nodes[1], 1);
3970
3971         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]).unwrap();
3972         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3973         {
3974                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
3975                 let events = nodes[0].node.get_and_clear_pending_msg_events();
3976                 assert_eq!(events.len(), 1);
3977                 match events[0] {
3978                         MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. }  } => {
3979                         },
3980                         _ => { panic!("Unexpected event"); }
3981                 }
3982         }
3983         let events = nodes[0].node.get_and_clear_pending_events();
3984         match events[0] {
3985                 Event::PaymentFailed { ref payment_hash, .. } => {
3986                         assert_eq!(*payment_hash, duplicate_payment_hash);
3987                 }
3988                 _ => panic!("Unexpected event"),
3989         }
3990
3991         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
3992         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
3993         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3994         assert!(updates.update_add_htlcs.is_empty());
3995         assert!(updates.update_fail_htlcs.is_empty());
3996         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3997         assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
3998         assert!(updates.update_fail_malformed_htlcs.is_empty());
3999         check_added_monitors!(nodes[1], 1);
4000
4001         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
4002         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4003
4004         let events = nodes[0].node.get_and_clear_pending_events();
4005         match events[0] {
4006                 Event::PaymentSent { ref payment_preimage } => {
4007                         assert_eq!(*payment_preimage, our_payment_preimage);
4008                 }
4009                 _ => panic!("Unexpected event"),
4010         }
4011 }
4012
4013 #[test]
4014 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4015         let nodes = create_network(2, &[None, None]);
4016
4017         // Create some initial channels
4018         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
4019
4020         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
4021         let local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
4022         assert_eq!(local_txn[0].input.len(), 1);
4023         check_spends!(local_txn[0], chan_1.3.clone());
4024
4025         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4026         nodes[1].node.claim_funds(payment_preimage);
4027         check_added_monitors!(nodes[1], 1);
4028         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4029         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 1);
4030         let events = nodes[1].node.get_and_clear_pending_msg_events();
4031         match events[0] {
4032                 MessageSendEvent::UpdateHTLCs { .. } => {},
4033                 _ => panic!("Unexpected event"),
4034         }
4035         match events[1] {
4036                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4037                 _ => panic!("Unexepected event"),
4038         }
4039         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4040         assert_eq!(node_txn[0].input.len(), 1);
4041         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4042         check_spends!(node_txn[0], local_txn[0].clone());
4043
4044         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4045         let spend_txn = check_spendable_outputs!(nodes[1], 1);
4046         assert_eq!(spend_txn.len(), 2);
4047         check_spends!(spend_txn[0], node_txn[0].clone());
4048         check_spends!(spend_txn[1], node_txn[2].clone());
4049 }
4050
4051 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4052         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4053         // unrevoked commitment transaction.
4054         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4055         // a remote RAA before they could be failed backwards (and combinations thereof).
4056         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4057         // use the same payment hashes.
4058         // Thus, we use a six-node network:
4059         //
4060         // A \         / E
4061         //    - C - D -
4062         // B /         \ F
4063         // And test where C fails back to A/B when D announces its latest commitment transaction
4064         let nodes = create_network(6, &[None, None, None, None, None, None]);
4065
4066         create_announced_chan_between_nodes(&nodes, 0, 2, LocalFeatures::new(), LocalFeatures::new());
4067         create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
4068         let chan = create_announced_chan_between_nodes(&nodes, 2, 3, LocalFeatures::new(), LocalFeatures::new());
4069         create_announced_chan_between_nodes(&nodes, 3, 4, LocalFeatures::new(), LocalFeatures::new());
4070         create_announced_chan_between_nodes(&nodes, 3, 5, LocalFeatures::new(), LocalFeatures::new());
4071
4072         // Rebalance and check output sanity...
4073         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
4074         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
4075         assert_eq!(nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn[0].output.len(), 2);
4076
4077         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
4078         // 0th HTLC:
4079         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
4080         // 1st HTLC:
4081         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
4082         let route = nodes[1].router.get_route(&nodes[5].node.get_our_node_id(), None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV).unwrap();
4083         // 2nd HTLC:
4084         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
4085         // 3rd HTLC:
4086         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
4087         // 4th HTLC:
4088         let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4089         // 5th HTLC:
4090         let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4091         let route = nodes[1].router.get_route(&nodes[5].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
4092         // 6th HTLC:
4093         send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
4094         // 7th HTLC:
4095         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
4096
4097         // 8th HTLC:
4098         let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4099         // 9th HTLC:
4100         let route = nodes[1].router.get_route(&nodes[5].node.get_our_node_id(), None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV).unwrap();
4101         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
4102
4103         // 10th HTLC:
4104         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
4105         // 11th HTLC:
4106         let route = nodes[1].router.get_route(&nodes[5].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
4107         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
4108
4109         // Double-check that six of the new HTLC were added
4110         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
4111         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
4112         assert_eq!(nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.len(), 1);
4113         assert_eq!(nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn[0].output.len(), 8);
4114
4115         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
4116         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
4117         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1));
4118         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3));
4119         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5));
4120         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6));
4121         check_added_monitors!(nodes[4], 0);
4122         expect_pending_htlcs_forwardable!(nodes[4]);
4123         check_added_monitors!(nodes[4], 1);
4124
4125         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
4126         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]).unwrap();
4127         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]).unwrap();
4128         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]).unwrap();
4129         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]).unwrap();
4130         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
4131
4132         // Fail 3rd below-dust and 7th above-dust HTLCs
4133         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2));
4134         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4));
4135         check_added_monitors!(nodes[5], 0);
4136         expect_pending_htlcs_forwardable!(nodes[5]);
4137         check_added_monitors!(nodes[5], 1);
4138
4139         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
4140         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]).unwrap();
4141         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]).unwrap();
4142         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
4143
4144         let ds_prev_commitment_tx = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
4145
4146         expect_pending_htlcs_forwardable!(nodes[3]);
4147         check_added_monitors!(nodes[3], 1);
4148         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
4149         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]).unwrap();
4150         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]).unwrap();
4151         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]).unwrap();
4152         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]).unwrap();
4153         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]).unwrap();
4154         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]).unwrap();
4155         if deliver_last_raa {
4156                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
4157         } else {
4158                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
4159         }
4160
4161         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
4162         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
4163         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
4164         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
4165         //
4166         // We now broadcast the latest commitment transaction, which *should* result in failures for
4167         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
4168         // the non-broadcast above-dust HTLCs.
4169         //
4170         // Alternatively, we may broadcast the previous commitment transaction, which should only
4171         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
4172         let ds_last_commitment_tx = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
4173
4174         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4175         if announce_latest {
4176                 nodes[2].chain_monitor.block_connected_checked(&header, 1, &[&ds_last_commitment_tx[0]], &[1; 1]);
4177         } else {
4178                 nodes[2].chain_monitor.block_connected_checked(&header, 1, &[&ds_prev_commitment_tx[0]], &[1; 1]);
4179         }
4180         connect_blocks(&nodes[2].chain_monitor, ANTI_REORG_DELAY - 1, 1, true,  header.bitcoin_hash());
4181         check_closed_broadcast!(nodes[2]);
4182         expect_pending_htlcs_forwardable!(nodes[2]);
4183         check_added_monitors!(nodes[2], 2);
4184
4185         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
4186         assert_eq!(cs_msgs.len(), 2);
4187         let mut a_done = false;
4188         for msg in cs_msgs {
4189                 match msg {
4190                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
4191                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
4192                                 // should be failed-backwards here.
4193                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
4194                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
4195                                         for htlc in &updates.update_fail_htlcs {
4196                                                 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 });
4197                                         }
4198                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
4199                                         assert!(!a_done);
4200                                         a_done = true;
4201                                         &nodes[0]
4202                                 } else {
4203                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
4204                                         for htlc in &updates.update_fail_htlcs {
4205                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
4206                                         }
4207                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
4208                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
4209                                         &nodes[1]
4210                                 };
4211                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
4212                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]).unwrap();
4213                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]).unwrap();
4214                                 if announce_latest {
4215                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]).unwrap();
4216                                         if *node_id == nodes[0].node.get_our_node_id() {
4217                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]).unwrap();
4218                                         }
4219                                 }
4220                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
4221                         },
4222                         _ => panic!("Unexpected event"),
4223                 }
4224         }
4225
4226         let as_events = nodes[0].node.get_and_clear_pending_events();
4227         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
4228         let mut as_failds = HashSet::new();
4229         for event in as_events.iter() {
4230                 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
4231                         assert!(as_failds.insert(*payment_hash));
4232                         if *payment_hash != payment_hash_2 {
4233                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
4234                         } else {
4235                                 assert!(!rejected_by_dest);
4236                         }
4237                 } else { panic!("Unexpected event"); }
4238         }
4239         assert!(as_failds.contains(&payment_hash_1));
4240         assert!(as_failds.contains(&payment_hash_2));
4241         if announce_latest {
4242                 assert!(as_failds.contains(&payment_hash_3));
4243                 assert!(as_failds.contains(&payment_hash_5));
4244         }
4245         assert!(as_failds.contains(&payment_hash_6));
4246
4247         let bs_events = nodes[1].node.get_and_clear_pending_events();
4248         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
4249         let mut bs_failds = HashSet::new();
4250         for event in bs_events.iter() {
4251                 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
4252                         assert!(bs_failds.insert(*payment_hash));
4253                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
4254                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
4255                         } else {
4256                                 assert!(!rejected_by_dest);
4257                         }
4258                 } else { panic!("Unexpected event"); }
4259         }
4260         assert!(bs_failds.contains(&payment_hash_1));
4261         assert!(bs_failds.contains(&payment_hash_2));
4262         if announce_latest {
4263                 assert!(bs_failds.contains(&payment_hash_4));
4264         }
4265         assert!(bs_failds.contains(&payment_hash_5));
4266
4267         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
4268         // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
4269         // to unknown-preimage-etc, B should have gotten 2. Thus, in the
4270         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
4271         // PaymentFailureNetworkUpdates.
4272         let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4273         assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
4274         let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4275         assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
4276         for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
4277                 match event {
4278                         &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
4279                         _ => panic!("Unexpected event"),
4280                 }
4281         }
4282 }
4283
4284 #[test]
4285 fn test_fail_backwards_latest_remote_announce_a() {
4286         do_test_fail_backwards_unrevoked_remote_announce(false, true);
4287 }
4288
4289 #[test]
4290 fn test_fail_backwards_latest_remote_announce_b() {
4291         do_test_fail_backwards_unrevoked_remote_announce(true, true);
4292 }
4293
4294 #[test]
4295 fn test_fail_backwards_previous_remote_announce() {
4296         do_test_fail_backwards_unrevoked_remote_announce(false, false);
4297         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
4298         // tested for in test_commitment_revoked_fail_backward_exhaustive()
4299 }
4300
4301 #[test]
4302 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
4303         let nodes = create_network(2, &[None, None]);
4304
4305         // Create some initial channels
4306         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
4307
4308         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
4309         let local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
4310         assert_eq!(local_txn[0].input.len(), 1);
4311         check_spends!(local_txn[0], chan_1.3.clone());
4312
4313         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
4314         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4315         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 200);
4316         check_closed_broadcast!(nodes[0]);
4317
4318         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4319         assert_eq!(node_txn[0].input.len(), 1);
4320         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4321         check_spends!(node_txn[0], local_txn[0].clone());
4322
4323         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
4324         let spend_txn = check_spendable_outputs!(nodes[0], 1);
4325         assert_eq!(spend_txn.len(), 8);
4326         assert_eq!(spend_txn[0], spend_txn[2]);
4327         assert_eq!(spend_txn[0], spend_txn[4]);
4328         assert_eq!(spend_txn[0], spend_txn[6]);
4329         assert_eq!(spend_txn[1], spend_txn[3]);
4330         assert_eq!(spend_txn[1], spend_txn[5]);
4331         assert_eq!(spend_txn[1], spend_txn[7]);
4332         check_spends!(spend_txn[0], local_txn[0].clone());
4333         check_spends!(spend_txn[1], node_txn[0].clone());
4334 }
4335
4336 #[test]
4337 fn test_static_output_closing_tx() {
4338         let nodes = create_network(2, &[None, None]);
4339
4340         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
4341
4342         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4343         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
4344
4345         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4346         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
4347         let spend_txn = check_spendable_outputs!(nodes[0], 2);
4348         assert_eq!(spend_txn.len(), 1);
4349         check_spends!(spend_txn[0], closing_tx.clone());
4350
4351         nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
4352         let spend_txn = check_spendable_outputs!(nodes[1], 2);
4353         assert_eq!(spend_txn.len(), 1);
4354         check_spends!(spend_txn[0], closing_tx);
4355 }
4356
4357 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
4358         let nodes = create_network(2, &[None, None]);
4359         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
4360
4361         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
4362
4363         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
4364         // present in B's local commitment transaction, but none of A's commitment transactions.
4365         assert!(nodes[1].node.claim_funds(our_payment_preimage));
4366         check_added_monitors!(nodes[1], 1);
4367
4368         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4369         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]).unwrap();
4370         let events = nodes[0].node.get_and_clear_pending_events();
4371         assert_eq!(events.len(), 1);
4372         match events[0] {
4373                 Event::PaymentSent { payment_preimage } => {
4374                         assert_eq!(payment_preimage, our_payment_preimage);
4375                 },
4376                 _ => panic!("Unexpected event"),
4377         }
4378
4379         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed).unwrap();
4380         check_added_monitors!(nodes[0], 1);
4381         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4382         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0).unwrap();
4383         check_added_monitors!(nodes[1], 1);
4384
4385         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4386         for i in 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + CHAN_CONFIRM_DEPTH + 1 {
4387                 nodes[1].chain_monitor.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
4388                 header.prev_blockhash = header.bitcoin_hash();
4389         }
4390         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
4391         check_closed_broadcast!(nodes[1]);
4392 }
4393
4394 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
4395         let mut nodes = create_network(2, &[None, None]);
4396         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
4397
4398         let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), if use_dust { 50000 } else { 3000000 }, TEST_FINAL_CLTV).unwrap();
4399         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
4400         nodes[0].node.send_payment(route, payment_hash).unwrap();
4401         check_added_monitors!(nodes[0], 1);
4402
4403         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4404
4405         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
4406         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
4407         // to "time out" the HTLC.
4408
4409         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4410         for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
4411                 nodes[0].chain_monitor.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
4412                 header.prev_blockhash = header.bitcoin_hash();
4413         }
4414         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
4415         check_closed_broadcast!(nodes[0]);
4416 }
4417
4418 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
4419         let nodes = create_network(3, &[None, None, None]);
4420         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
4421
4422         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
4423         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
4424         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
4425         // actually revoked.
4426         let htlc_value = if use_dust { 50000 } else { 3000000 };
4427         let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
4428         assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash));
4429         expect_pending_htlcs_forwardable!(nodes[1]);
4430         check_added_monitors!(nodes[1], 1);
4431
4432         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4433         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]).unwrap();
4434         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed).unwrap();
4435         check_added_monitors!(nodes[0], 1);
4436         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4437         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0).unwrap();
4438         check_added_monitors!(nodes[1], 1);
4439         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1).unwrap();
4440         check_added_monitors!(nodes[1], 1);
4441         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4442
4443         if check_revoke_no_close {
4444                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
4445                 check_added_monitors!(nodes[0], 1);
4446         }
4447
4448         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4449         for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
4450                 nodes[0].chain_monitor.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
4451                 header.prev_blockhash = header.bitcoin_hash();
4452         }
4453         if !check_revoke_no_close {
4454                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
4455                 check_closed_broadcast!(nodes[0]);
4456         } else {
4457                 let events = nodes[0].node.get_and_clear_pending_events();
4458                 assert_eq!(events.len(), 1);
4459                 match events[0] {
4460                         Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
4461                                 assert_eq!(payment_hash, our_payment_hash);
4462                                 assert!(rejected_by_dest);
4463                         },
4464                         _ => panic!("Unexpected event"),
4465                 }
4466         }
4467 }
4468
4469 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
4470 // There are only a few cases to test here:
4471 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
4472 //    broadcastable commitment transactions result in channel closure,
4473 //  * its included in an unrevoked-but-previous remote commitment transaction,
4474 //  * its included in the latest remote or local commitment transactions.
4475 // We test each of the three possible commitment transactions individually and use both dust and
4476 // non-dust HTLCs.
4477 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
4478 // assume they are handled the same across all six cases, as both outbound and inbound failures are
4479 // tested for at least one of the cases in other tests.
4480 #[test]
4481 fn htlc_claim_single_commitment_only_a() {
4482         do_htlc_claim_local_commitment_only(true);
4483         do_htlc_claim_local_commitment_only(false);
4484
4485         do_htlc_claim_current_remote_commitment_only(true);
4486         do_htlc_claim_current_remote_commitment_only(false);
4487 }
4488
4489 #[test]
4490 fn htlc_claim_single_commitment_only_b() {
4491         do_htlc_claim_previous_remote_commitment_only(true, false);
4492         do_htlc_claim_previous_remote_commitment_only(false, false);
4493         do_htlc_claim_previous_remote_commitment_only(true, true);
4494         do_htlc_claim_previous_remote_commitment_only(false, true);
4495 }
4496
4497 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>)
4498         where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
4499                                 F2: FnMut(),
4500 {
4501         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);
4502 }
4503
4504 // test_case
4505 // 0: node1 fails backward
4506 // 1: final node fails backward
4507 // 2: payment completed but the user rejects the payment
4508 // 3: final node fails backward (but tamper onion payloads from node0)
4509 // 100: trigger error in the intermediate node and tamper returning fail_htlc
4510 // 200: trigger error in the final node and tamper returning fail_htlc
4511 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>)
4512         where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
4513                                 F2: for <'a> FnMut(&'a mut msgs::UpdateFailHTLC),
4514                                 F3: FnMut(),
4515 {
4516         use ln::msgs::HTLCFailChannelUpdate;
4517
4518         // reset block height
4519         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4520         for ix in 0..nodes.len() {
4521                 nodes[ix].chain_monitor.block_connected_checked(&header, 1, &Vec::new()[..], &[0; 0]);
4522         }
4523
4524         macro_rules! expect_event {
4525                 ($node: expr, $event_type: path) => {{
4526                         let events = $node.node.get_and_clear_pending_events();
4527                         assert_eq!(events.len(), 1);
4528                         match events[0] {
4529                                 $event_type { .. } => {},
4530                                 _ => panic!("Unexpected event"),
4531                         }
4532                 }}
4533         }
4534
4535         macro_rules! expect_htlc_forward {
4536                 ($node: expr) => {{
4537                         expect_event!($node, Event::PendingHTLCsForwardable);
4538                         $node.node.process_pending_htlc_forwards();
4539                 }}
4540         }
4541
4542         // 0 ~~> 2 send payment
4543         nodes[0].node.send_payment(route.clone(), payment_hash.clone()).unwrap();
4544         check_added_monitors!(nodes[0], 1);
4545         let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4546         // temper update_add (0 => 1)
4547         let mut update_add_0 = update_0.update_add_htlcs[0].clone();
4548         if test_case == 0 || test_case == 3 || test_case == 100 {
4549                 callback_msg(&mut update_add_0);
4550                 callback_node();
4551         }
4552         // 0 => 1 update_add & CS
4553         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_0).unwrap();
4554         commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
4555
4556         let update_1_0 = match test_case {
4557                 0|100 => { // intermediate node failure; fail backward to 0
4558                         let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4559                         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));
4560                         update_1_0
4561                 },
4562                 1|2|3|200 => { // final node failure; forwarding to 2
4563                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4564                         // forwarding on 1
4565                         if test_case != 200 {
4566                                 callback_node();
4567                         }
4568                         expect_htlc_forward!(&nodes[1]);
4569
4570                         let update_1 = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
4571                         check_added_monitors!(&nodes[1], 1);
4572                         assert_eq!(update_1.update_add_htlcs.len(), 1);
4573                         // tamper update_add (1 => 2)
4574                         let mut update_add_1 = update_1.update_add_htlcs[0].clone();
4575                         if test_case != 3 && test_case != 200 {
4576                                 callback_msg(&mut update_add_1);
4577                         }
4578
4579                         // 1 => 2
4580                         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_1).unwrap();
4581                         commitment_signed_dance!(nodes[2], nodes[1], update_1.commitment_signed, false, true);
4582
4583                         if test_case == 2 || test_case == 200 {
4584                                 expect_htlc_forward!(&nodes[2]);
4585                                 expect_event!(&nodes[2], Event::PaymentReceived);
4586                                 callback_node();
4587                                 expect_pending_htlcs_forwardable!(nodes[2]);
4588                         }
4589
4590                         let update_2_1 = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4591                         if test_case == 2 || test_case == 200 {
4592                                 check_added_monitors!(&nodes[2], 1);
4593                         }
4594                         assert!(update_2_1.update_fail_htlcs.len() == 1);
4595
4596                         let mut fail_msg = update_2_1.update_fail_htlcs[0].clone();
4597                         if test_case == 200 {
4598                                 callback_fail(&mut fail_msg);
4599                         }
4600
4601                         // 2 => 1
4602                         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_msg).unwrap();
4603                         commitment_signed_dance!(nodes[1], nodes[2], update_2_1.commitment_signed, true);
4604
4605                         // backward fail on 1
4606                         let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4607                         assert!(update_1_0.update_fail_htlcs.len() == 1);
4608                         update_1_0
4609                 },
4610                 _ => unreachable!(),
4611         };
4612
4613         // 1 => 0 commitment_signed_dance
4614         if update_1_0.update_fail_htlcs.len() > 0 {
4615                 let mut fail_msg = update_1_0.update_fail_htlcs[0].clone();
4616                 if test_case == 100 {
4617                         callback_fail(&mut fail_msg);
4618                 }
4619                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg).unwrap();
4620         } else {
4621                 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_1_0.update_fail_malformed_htlcs[0]).unwrap();
4622         };
4623
4624         commitment_signed_dance!(nodes[0], nodes[1], update_1_0.commitment_signed, false, true);
4625
4626         let events = nodes[0].node.get_and_clear_pending_events();
4627         assert_eq!(events.len(), 1);
4628         if let &Event::PaymentFailed { payment_hash:_, ref rejected_by_dest, ref error_code } = &events[0] {
4629                 assert_eq!(*rejected_by_dest, !expected_retryable);
4630                 assert_eq!(*error_code, expected_error_code);
4631         } else {
4632                 panic!("Uexpected event");
4633         }
4634
4635         let events = nodes[0].node.get_and_clear_pending_msg_events();
4636         if expected_channel_update.is_some() {
4637                 assert_eq!(events.len(), 1);
4638                 match events[0] {
4639                         MessageSendEvent::PaymentFailureNetworkUpdate { ref update } => {
4640                                 match update {
4641                                         &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {
4642                                                 if let HTLCFailChannelUpdate::ChannelUpdateMessage { .. } = expected_channel_update.unwrap() {} else {
4643                                                         panic!("channel_update not found!");
4644                                                 }
4645                                         },
4646                                         &HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, ref is_permanent } => {
4647                                                 if let HTLCFailChannelUpdate::ChannelClosed { short_channel_id: ref expected_short_channel_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
4648                                                         assert!(*short_channel_id == *expected_short_channel_id);
4649                                                         assert!(*is_permanent == *expected_is_permanent);
4650                                                 } else {
4651                                                         panic!("Unexpected message event");
4652                                                 }
4653                                         },
4654                                         &HTLCFailChannelUpdate::NodeFailure { ref node_id, ref is_permanent } => {
4655                                                 if let HTLCFailChannelUpdate::NodeFailure { node_id: ref expected_node_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
4656                                                         assert!(*node_id == *expected_node_id);
4657                                                         assert!(*is_permanent == *expected_is_permanent);
4658                                                 } else {
4659                                                         panic!("Unexpected message event");
4660                                                 }
4661                                         },
4662                                 }
4663                         },
4664                         _ => panic!("Unexpected message event"),
4665                 }
4666         } else {
4667                 assert_eq!(events.len(), 0);
4668         }
4669 }
4670
4671 impl msgs::ChannelUpdate {
4672         fn dummy() -> msgs::ChannelUpdate {
4673                 use secp256k1::ffi::Signature as FFISignature;
4674                 use secp256k1::Signature;
4675                 msgs::ChannelUpdate {
4676                         signature: Signature::from(FFISignature::new()),
4677                         contents: msgs::UnsignedChannelUpdate {
4678                                 chain_hash: Sha256dHash::hash(&vec![0u8][..]),
4679                                 short_channel_id: 0,
4680                                 timestamp: 0,
4681                                 flags: 0,
4682                                 cltv_expiry_delta: 0,
4683                                 htlc_minimum_msat: 0,
4684                                 fee_base_msat: 0,
4685                                 fee_proportional_millionths: 0,
4686                                 excess_data: vec![],
4687                         }
4688                 }
4689         }
4690 }
4691
4692 #[test]
4693 fn test_onion_failure() {
4694         use ln::msgs::ChannelUpdate;
4695         use ln::channelmanager::CLTV_FAR_FAR_AWAY;
4696         use secp256k1;
4697
4698         const BADONION: u16 = 0x8000;
4699         const PERM: u16 = 0x4000;
4700         const NODE: u16 = 0x2000;
4701         const UPDATE: u16 = 0x1000;
4702
4703         let mut nodes = create_network(3, &[None, None, None]);
4704         for node in nodes.iter() {
4705                 *node.keys_manager.override_session_priv.lock().unwrap() = Some(SecretKey::from_slice(&[3; 32]).unwrap());
4706         }
4707         let channels = [create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new()), create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new())];
4708         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
4709         let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV).unwrap();
4710         // positve case
4711         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 40000);
4712
4713         // intermediate node failure
4714         run_onion_failure_test("invalid_realm", 0, &nodes, &route, &payment_hash, |msg| {
4715                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4716                 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
4717                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4718                 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
4719                 onion_payloads[0].realm = 3;
4720                 msg.onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
4721         }, ||{}, true, Some(PERM|1), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));//XXX incremented channels idx here
4722
4723         // final node failure
4724         run_onion_failure_test("invalid_realm", 3, &nodes, &route, &payment_hash, |msg| {
4725                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4726                 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
4727                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4728                 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
4729                 onion_payloads[1].realm = 3;
4730                 msg.onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
4731         }, ||{}, false, Some(PERM|1), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
4732
4733         // the following three with run_onion_failure_test_with_fail_intercept() test only the origin node
4734         // receiving simulated fail messages
4735         // intermediate node failure
4736         run_onion_failure_test_with_fail_intercept("temporary_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
4737                 // trigger error
4738                 msg.amount_msat -= 1;
4739         }, |msg| {
4740                 // and tamper returning error message
4741                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4742                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4743                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], NODE|2, &[0;0]);
4744         }, ||{}, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: false}));
4745
4746         // final node failure
4747         run_onion_failure_test_with_fail_intercept("temporary_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
4748                 // and tamper returning error message
4749                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4750                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4751                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], NODE|2, &[0;0]);
4752         }, ||{
4753                 nodes[2].node.fail_htlc_backwards(&payment_hash);
4754         }, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: false}));
4755
4756         // intermediate node failure
4757         run_onion_failure_test_with_fail_intercept("permanent_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
4758                 msg.amount_msat -= 1;
4759         }, |msg| {
4760                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4761                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4762                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|2, &[0;0]);
4763         }, ||{}, true, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: true}));
4764
4765         // final node failure
4766         run_onion_failure_test_with_fail_intercept("permanent_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
4767                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4768                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4769                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|2, &[0;0]);
4770         }, ||{
4771                 nodes[2].node.fail_htlc_backwards(&payment_hash);
4772         }, false, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: true}));
4773
4774         // intermediate node failure
4775         run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
4776                 msg.amount_msat -= 1;
4777         }, |msg| {
4778                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4779                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4780                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|3, &[0;0]);
4781         }, ||{
4782                 nodes[2].node.fail_htlc_backwards(&payment_hash);
4783         }, true, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: true}));
4784
4785         // final node failure
4786         run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
4787                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4788                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4789                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|3, &[0;0]);
4790         }, ||{
4791                 nodes[2].node.fail_htlc_backwards(&payment_hash);
4792         }, false, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: true}));
4793
4794         run_onion_failure_test("invalid_onion_version", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.version = 1; }, ||{}, true,
4795                 Some(BADONION|PERM|4), None);
4796
4797         run_onion_failure_test("invalid_onion_hmac", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.hmac = [3; 32]; }, ||{}, true,
4798                 Some(BADONION|PERM|5), None);
4799
4800         run_onion_failure_test("invalid_onion_key", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.public_key = Err(secp256k1::Error::InvalidPublicKey);}, ||{}, true,
4801                 Some(BADONION|PERM|6), None);
4802
4803         run_onion_failure_test_with_fail_intercept("temporary_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
4804                 msg.amount_msat -= 1;
4805         }, |msg| {
4806                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4807                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4808                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], UPDATE|7, &ChannelUpdate::dummy().encode_with_len()[..]);
4809         }, ||{}, true, Some(UPDATE|7), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
4810
4811         run_onion_failure_test_with_fail_intercept("permanent_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
4812                 msg.amount_msat -= 1;
4813         }, |msg| {
4814                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4815                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4816                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|8, &[0;0]);
4817                 // short_channel_id from the processing node
4818         }, ||{}, true, Some(PERM|8), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
4819
4820         run_onion_failure_test_with_fail_intercept("required_channel_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
4821                 msg.amount_msat -= 1;
4822         }, |msg| {
4823                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4824                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4825                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|9, &[0;0]);
4826                 // short_channel_id from the processing node
4827         }, ||{}, true, Some(PERM|9), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
4828
4829         let mut bogus_route = route.clone();
4830         bogus_route.hops[1].short_channel_id -= 1;
4831         run_onion_failure_test("unknown_next_peer", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(PERM|10),
4832           Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: bogus_route.hops[1].short_channel_id, is_permanent:true}));
4833
4834         let amt_to_forward = nodes[1].node.channel_state.lock().unwrap().by_id.get(&channels[1].2).unwrap().get_their_htlc_minimum_msat() - 1;
4835         let mut bogus_route = route.clone();
4836         let route_len = bogus_route.hops.len();
4837         bogus_route.hops[route_len-1].fee_msat = amt_to_forward;
4838         run_onion_failure_test("amount_below_minimum", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(UPDATE|11), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
4839
4840         //TODO: with new config API, we will be able to generate both valid and
4841         //invalid channel_update cases.
4842         run_onion_failure_test("fee_insufficient", 0, &nodes, &route, &payment_hash, |msg| {
4843                 msg.amount_msat -= 1;
4844         }, || {}, true, Some(UPDATE|12), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
4845
4846         run_onion_failure_test("incorrect_cltv_expiry", 0, &nodes, &route, &payment_hash, |msg| {
4847                 // need to violate: cltv_expiry - cltv_expiry_delta >= outgoing_cltv_value
4848                 msg.cltv_expiry -= 1;
4849         }, || {}, true, Some(UPDATE|13), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
4850
4851         run_onion_failure_test("expiry_too_soon", 0, &nodes, &route, &payment_hash, |msg| {
4852                 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
4853                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4854                 nodes[1].chain_monitor.block_connected_checked(&header, height, &Vec::new()[..], &[0; 0]);
4855         }, ||{}, true, Some(UPDATE|14), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
4856
4857         run_onion_failure_test("unknown_payment_hash", 2, &nodes, &route, &payment_hash, |_| {}, || {
4858                 nodes[2].node.fail_htlc_backwards(&payment_hash);
4859         }, false, Some(PERM|15), None);
4860
4861         run_onion_failure_test("final_expiry_too_soon", 1, &nodes, &route, &payment_hash, |msg| {
4862                 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
4863                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4864                 nodes[2].chain_monitor.block_connected_checked(&header, height, &Vec::new()[..], &[0; 0]);
4865         }, || {}, true, Some(17), None);
4866
4867         run_onion_failure_test("final_incorrect_cltv_expiry", 1, &nodes, &route, &payment_hash, |_| {}, || {
4868                 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().borrow_parts().forward_htlcs.iter_mut() {
4869                         for f in pending_forwards.iter_mut() {
4870                                 match f {
4871                                         &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
4872                                                 forward_info.outgoing_cltv_value += 1,
4873                                         _ => {},
4874                                 }
4875                         }
4876                 }
4877         }, true, Some(18), None);
4878
4879         run_onion_failure_test("final_incorrect_htlc_amount", 1, &nodes, &route, &payment_hash, |_| {}, || {
4880                 // violate amt_to_forward > msg.amount_msat
4881                 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().borrow_parts().forward_htlcs.iter_mut() {
4882                         for f in pending_forwards.iter_mut() {
4883                                 match f {
4884                                         &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
4885                                                 forward_info.amt_to_forward -= 1,
4886                                         _ => {},
4887                                 }
4888                         }
4889                 }
4890         }, true, Some(19), None);
4891
4892         run_onion_failure_test("channel_disabled", 0, &nodes, &route, &payment_hash, |_| {}, || {
4893                 // disconnect event to the channel between nodes[1] ~ nodes[2]
4894                 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
4895                 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4896         }, true, Some(UPDATE|20), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
4897         reconnect_nodes(&nodes[1], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4898
4899         run_onion_failure_test("expiry_too_far", 0, &nodes, &route, &payment_hash, |msg| {
4900                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4901                 let mut route = route.clone();
4902                 let height = 1;
4903                 route.hops[1].cltv_expiry_delta += CLTV_FAR_FAR_AWAY + route.hops[0].cltv_expiry_delta + 1;
4904                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4905                 let (onion_payloads, _, htlc_cltv) = onion_utils::build_onion_payloads(&route, height).unwrap();
4906                 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
4907                 msg.cltv_expiry = htlc_cltv;
4908                 msg.onion_routing_packet = onion_packet;
4909         }, ||{}, true, Some(21), None);
4910 }
4911
4912 #[test]
4913 #[should_panic]
4914 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
4915         let nodes = create_network(2, &[None, None]);
4916         //Force duplicate channel ids
4917         for node in nodes.iter() {
4918                 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
4919         }
4920
4921         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
4922         let channel_value_satoshis=10000;
4923         let push_msat=10001;
4924         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42).unwrap();
4925         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
4926         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), LocalFeatures::new(), &node0_to_1_send_open_channel).unwrap();
4927
4928         //Create a second channel with a channel_id collision
4929         assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42).is_err());
4930 }
4931
4932 #[test]
4933 fn bolt2_open_channel_sending_node_checks_part2() {
4934         let nodes = create_network(2, &[None, None]);
4935
4936         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
4937         let channel_value_satoshis=2^24;
4938         let push_msat=10001;
4939         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42).is_err());
4940
4941         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
4942         let channel_value_satoshis=10000;
4943         // Test when push_msat is equal to 1000 * funding_satoshis.
4944         let push_msat=1000*channel_value_satoshis+1;
4945         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42).is_err());
4946
4947         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
4948         let channel_value_satoshis=10000;
4949         let push_msat=10001;
4950         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42).is_ok()); //Create a valid channel
4951         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
4952         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
4953
4954         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
4955         // 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
4956         assert!(node0_to_1_send_open_channel.channel_flags<=1);
4957
4958         // 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.
4959         assert!(BREAKDOWN_TIMEOUT>0);
4960         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
4961
4962         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
4963         let chain_hash=genesis_block(Network::Testnet).header.bitcoin_hash();
4964         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
4965
4966         // 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.
4967         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
4968         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
4969         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
4970         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_basepoint.serialize()).is_ok());
4971         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
4972 }
4973
4974 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
4975 // 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.
4976 //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.
4977
4978 #[test]
4979 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
4980         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
4981         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
4982         let mut nodes = create_network(2, &[None, None]);
4983         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, LocalFeatures::new(), LocalFeatures::new());
4984         let mut route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4985         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4986
4987         route.hops[0].fee_msat = 0;
4988
4989         let err = nodes[0].node.send_payment(route, our_payment_hash);
4990
4991         if let Err(APIError::ChannelUnavailable{err}) = err {
4992                 assert_eq!(err, "Cannot send less than their minimum HTLC value");
4993         } else {
4994                 assert!(false);
4995         }
4996 }
4997
4998 #[test]
4999 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
5000         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
5001         //It is enforced when constructing a route.
5002         let mut nodes = create_network(2, &[None, None]);
5003         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 0, LocalFeatures::new(), LocalFeatures::new());
5004         let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000000, 500000001).unwrap();
5005         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5006
5007         let err = nodes[0].node.send_payment(route, our_payment_hash);
5008
5009         if let Err(APIError::RouteError{err}) = err {
5010                 assert_eq!(err, "Channel CLTV overflowed?!");
5011         } else {
5012                 assert!(false);
5013         }
5014 }
5015
5016 #[test]
5017 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
5018         //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.
5019         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
5020         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
5021         let mut nodes = create_network(2, &[None, None]);
5022         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, LocalFeatures::new(), LocalFeatures::new());
5023         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().their_max_accepted_htlcs as u64;
5024
5025         for i in 0..max_accepted_htlcs {
5026                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
5027                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5028                 let payment_event = {
5029                         nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5030                         check_added_monitors!(nodes[0], 1);
5031
5032                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5033                         assert_eq!(events.len(), 1);
5034                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
5035                                 assert_eq!(htlcs[0].htlc_id, i);
5036                         } else {
5037                                 assert!(false);
5038                         }
5039                         SendEvent::from_event(events.remove(0))
5040                 };
5041                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
5042                 check_added_monitors!(nodes[1], 0);
5043                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5044
5045                 expect_pending_htlcs_forwardable!(nodes[1]);
5046                 expect_payment_received!(nodes[1], our_payment_hash, 100000);
5047         }
5048         let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
5049         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5050         let err = nodes[0].node.send_payment(route, our_payment_hash);
5051
5052         if let Err(APIError::ChannelUnavailable{err}) = err {
5053                 assert_eq!(err, "Cannot push more than their max accepted HTLCs");
5054         } else {
5055                 assert!(false);
5056         }
5057 }
5058
5059 #[test]
5060 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
5061         //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.
5062         let mut nodes = create_network(2, &[None, None]);
5063         let channel_value = 100000;
5064         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, LocalFeatures::new(), LocalFeatures::new());
5065         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).their_max_htlc_value_in_flight_msat;
5066
5067         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
5068
5069         let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], max_in_flight+1, TEST_FINAL_CLTV).unwrap();
5070         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5071         let err = nodes[0].node.send_payment(route, our_payment_hash);
5072
5073         if let Err(APIError::ChannelUnavailable{err}) = err {
5074                 assert_eq!(err, "Cannot send value that would put us over the max HTLC value in flight our peer will accept");
5075         } else {
5076                 assert!(false);
5077         }
5078
5079         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
5080 }
5081
5082 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
5083 #[test]
5084 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
5085         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
5086         let mut nodes = create_network(2, &[None, None]);
5087         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, LocalFeatures::new(), LocalFeatures::new());
5088         let htlc_minimum_msat: u64;
5089         {
5090                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
5091                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
5092                 htlc_minimum_msat = channel.get_our_htlc_minimum_msat();
5093         }
5094         let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], htlc_minimum_msat, TEST_FINAL_CLTV).unwrap();
5095         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5096         nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5097         check_added_monitors!(nodes[0], 1);
5098         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5099         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
5100         let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5101         if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
5102                 assert_eq!(err, "Remote side tried to send less than our minimum HTLC value");
5103         } else {
5104                 assert!(false);
5105         }
5106         assert!(nodes[1].node.list_channels().is_empty());
5107         check_closed_broadcast!(nodes[1]);
5108 }
5109
5110 #[test]
5111 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
5112         //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
5113         let mut nodes = create_network(2, &[None, None]);
5114         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, LocalFeatures::new(), LocalFeatures::new());
5115
5116         let their_channel_reserve = get_channel_value_stat!(nodes[0], chan.2).channel_reserve_msat;
5117
5118         let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 5000000-their_channel_reserve, TEST_FINAL_CLTV).unwrap();
5119         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5120         nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5121         check_added_monitors!(nodes[0], 1);
5122         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5123
5124         updates.update_add_htlcs[0].amount_msat = 5000000-their_channel_reserve+1;
5125         let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5126
5127         if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
5128                 assert_eq!(err, "Remote HTLC add would put them over their reserve value");
5129         } else {
5130                 assert!(false);
5131         }
5132
5133         assert!(nodes[1].node.list_channels().is_empty());
5134         check_closed_broadcast!(nodes[1]);
5135 }
5136
5137 #[test]
5138 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
5139         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
5140         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
5141         let mut nodes = create_network(2, &[None, None]);
5142         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, LocalFeatures::new(), LocalFeatures::new());
5143         let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 3999999, TEST_FINAL_CLTV).unwrap();
5144         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5145
5146         let session_priv = SecretKey::from_slice(&{
5147                 let mut session_key = [0; 32];
5148                 let mut rng = thread_rng();
5149                 rng.fill_bytes(&mut session_key);
5150                 session_key
5151         }).expect("RNG is bad!");
5152
5153         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5154         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route, &session_priv).unwrap();
5155         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
5156         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, &our_payment_hash);
5157
5158         let mut msg = msgs::UpdateAddHTLC {
5159                 channel_id: chan.2,
5160                 htlc_id: 0,
5161                 amount_msat: 1000,
5162                 payment_hash: our_payment_hash,
5163                 cltv_expiry: htlc_cltv,
5164                 onion_routing_packet: onion_packet.clone(),
5165         };
5166
5167         for i in 0..super::channel::OUR_MAX_HTLCS {
5168                 msg.htlc_id = i as u64;
5169                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg).unwrap();
5170         }
5171         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
5172         let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
5173
5174         if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
5175                 assert_eq!(err, "Remote tried to push more than our max accepted HTLCs");
5176         } else {
5177                 assert!(false);
5178         }
5179
5180         assert!(nodes[1].node.list_channels().is_empty());
5181         check_closed_broadcast!(nodes[1]);
5182 }
5183
5184 #[test]
5185 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
5186         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
5187         let mut nodes = create_network(2, &[None, None]);
5188         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, LocalFeatures::new(), LocalFeatures::new());
5189         let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5190         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5191         nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5192         check_added_monitors!(nodes[0], 1);
5193         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5194         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).their_max_htlc_value_in_flight_msat + 1;
5195         let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5196
5197         if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
5198                 assert_eq!(err,"Remote HTLC add would put them over our max HTLC value");
5199         } else {
5200                 assert!(false);
5201         }
5202
5203         assert!(nodes[1].node.list_channels().is_empty());
5204         check_closed_broadcast!(nodes[1]);
5205 }
5206
5207 #[test]
5208 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
5209         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
5210         let mut nodes = create_network(2, &[None, None]);
5211         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, LocalFeatures::new(), LocalFeatures::new());
5212         let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 3999999, TEST_FINAL_CLTV).unwrap();
5213         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5214         nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5215         check_added_monitors!(nodes[0], 1);
5216         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5217         updates.update_add_htlcs[0].cltv_expiry = 500000000;
5218         let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5219
5220         if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
5221                 assert_eq!(err,"Remote provided CLTV expiry in seconds instead of block height");
5222         } else {
5223                 assert!(false);
5224         }
5225
5226         assert!(nodes[1].node.list_channels().is_empty());
5227         check_closed_broadcast!(nodes[1]);
5228 }
5229
5230 #[test]
5231 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
5232         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
5233         // We test this by first testing that that repeated HTLCs pass commitment signature checks
5234         // after disconnect and that non-sequential htlc_ids result in a channel failure.
5235         let mut nodes = create_network(2, &[None, None]);
5236         create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
5237         let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5238         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5239         nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5240         check_added_monitors!(nodes[0], 1);
5241         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5242         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
5243
5244         //Disconnect and Reconnect
5245         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5246         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5247         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
5248         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
5249         assert_eq!(reestablish_1.len(), 1);
5250         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
5251         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
5252         assert_eq!(reestablish_2.len(), 1);
5253         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
5254         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
5255         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
5256         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
5257
5258         //Resend HTLC
5259         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
5260         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
5261         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed).unwrap();
5262         check_added_monitors!(nodes[1], 1);
5263         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5264
5265         let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5266         if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
5267                 assert_eq!(err, "Remote skipped HTLC ID");
5268         } else {
5269                 assert!(false);
5270         }
5271
5272         assert!(nodes[1].node.list_channels().is_empty());
5273         check_closed_broadcast!(nodes[1]);
5274 }
5275
5276 #[test]
5277 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
5278         //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.
5279
5280         let mut nodes = create_network(2, &[None, None]);
5281         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
5282
5283         let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5284         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5285         nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5286         check_added_monitors!(nodes[0], 1);
5287         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5288         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
5289
5290         let update_msg = msgs::UpdateFulfillHTLC{
5291                 channel_id: chan.2,
5292                 htlc_id: 0,
5293                 payment_preimage: our_payment_preimage,
5294         };
5295
5296         let err = nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
5297
5298         if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
5299                 assert_eq!(err, "Remote tried to fulfill/fail HTLC before it had been committed");
5300         } else {
5301                 assert!(false);
5302         }
5303
5304         assert!(nodes[0].node.list_channels().is_empty());
5305         check_closed_broadcast!(nodes[0]);
5306 }
5307
5308 #[test]
5309 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
5310         //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.
5311
5312         let mut nodes = create_network(2, &[None, None]);
5313         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
5314
5315         let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5316         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5317         nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5318         check_added_monitors!(nodes[0], 1);
5319         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5320         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
5321
5322         let update_msg = msgs::UpdateFailHTLC{
5323                 channel_id: chan.2,
5324                 htlc_id: 0,
5325                 reason: msgs::OnionErrorPacket { data: Vec::new()},
5326         };
5327
5328         let err = nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
5329
5330         if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
5331                 assert_eq!(err, "Remote tried to fulfill/fail HTLC before it had been committed");
5332         } else {
5333                 assert!(false);
5334         }
5335
5336         assert!(nodes[0].node.list_channels().is_empty());
5337         check_closed_broadcast!(nodes[0]);
5338 }
5339
5340 #[test]
5341 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
5342         //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.
5343
5344         let mut nodes = create_network(2, &[None, None]);
5345         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
5346
5347         let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5348         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5349         nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5350         check_added_monitors!(nodes[0], 1);
5351         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5352         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
5353
5354         let update_msg = msgs::UpdateFailMalformedHTLC{
5355                 channel_id: chan.2,
5356                 htlc_id: 0,
5357                 sha256_of_onion: [1; 32],
5358                 failure_code: 0x8000,
5359         };
5360
5361         let err = nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
5362
5363         if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
5364                 assert_eq!(err, "Remote tried to fulfill/fail HTLC before it had been committed");
5365         } else {
5366                 assert!(false);
5367         }
5368
5369         assert!(nodes[0].node.list_channels().is_empty());
5370         check_closed_broadcast!(nodes[0]);
5371 }
5372
5373 #[test]
5374 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
5375         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
5376
5377         let nodes = create_network(2, &[None, None]);
5378         create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
5379
5380         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
5381
5382         nodes[1].node.claim_funds(our_payment_preimage);
5383         check_added_monitors!(nodes[1], 1);
5384
5385         let events = nodes[1].node.get_and_clear_pending_msg_events();
5386         assert_eq!(events.len(), 1);
5387         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
5388                 match events[0] {
5389                         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, .. } } => {
5390                                 assert!(update_add_htlcs.is_empty());
5391                                 assert_eq!(update_fulfill_htlcs.len(), 1);
5392                                 assert!(update_fail_htlcs.is_empty());
5393                                 assert!(update_fail_malformed_htlcs.is_empty());
5394                                 assert!(update_fee.is_none());
5395                                 update_fulfill_htlcs[0].clone()
5396                         },
5397                         _ => panic!("Unexpected event"),
5398                 }
5399         };
5400
5401         update_fulfill_msg.htlc_id = 1;
5402
5403         let err = nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
5404         if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
5405                 assert_eq!(err, "Remote tried to fulfill/fail an HTLC we couldn't find");
5406         } else {
5407                 assert!(false);
5408         }
5409
5410         assert!(nodes[0].node.list_channels().is_empty());
5411         check_closed_broadcast!(nodes[0]);
5412 }
5413
5414 #[test]
5415 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
5416         //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.
5417
5418         let nodes = create_network(2, &[None, None]);
5419         create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
5420
5421         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
5422
5423         nodes[1].node.claim_funds(our_payment_preimage);
5424         check_added_monitors!(nodes[1], 1);
5425
5426         let events = nodes[1].node.get_and_clear_pending_msg_events();
5427         assert_eq!(events.len(), 1);
5428         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
5429                 match events[0] {
5430                         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, .. } } => {
5431                                 assert!(update_add_htlcs.is_empty());
5432                                 assert_eq!(update_fulfill_htlcs.len(), 1);
5433                                 assert!(update_fail_htlcs.is_empty());
5434                                 assert!(update_fail_malformed_htlcs.is_empty());
5435                                 assert!(update_fee.is_none());
5436                                 update_fulfill_htlcs[0].clone()
5437                         },
5438                         _ => panic!("Unexpected event"),
5439                 }
5440         };
5441
5442         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
5443
5444         let err = nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
5445         if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
5446                 assert_eq!(err, "Remote tried to fulfill HTLC with an incorrect preimage");
5447         } else {
5448                 assert!(false);
5449         }
5450
5451         assert!(nodes[0].node.list_channels().is_empty());
5452         check_closed_broadcast!(nodes[0]);
5453 }
5454
5455
5456 #[test]
5457 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
5458         //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.
5459
5460         let mut nodes = create_network(2, &[None, None]);
5461         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, LocalFeatures::new(), LocalFeatures::new());
5462         let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5463         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5464         nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5465         check_added_monitors!(nodes[0], 1);
5466
5467         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5468         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
5469
5470         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
5471         check_added_monitors!(nodes[1], 0);
5472         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
5473
5474         let events = nodes[1].node.get_and_clear_pending_msg_events();
5475
5476         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
5477                 match events[0] {
5478                         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, .. } } => {
5479                                 assert!(update_add_htlcs.is_empty());
5480                                 assert!(update_fulfill_htlcs.is_empty());
5481                                 assert!(update_fail_htlcs.is_empty());
5482                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
5483                                 assert!(update_fee.is_none());
5484                                 update_fail_malformed_htlcs[0].clone()
5485                         },
5486                         _ => panic!("Unexpected event"),
5487                 }
5488         };
5489         update_msg.failure_code &= !0x8000;
5490         let err = nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
5491         if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
5492                 assert_eq!(err, "Got update_fail_malformed_htlc with BADONION not set");
5493         } else {
5494                 assert!(false);
5495         }
5496
5497         assert!(nodes[0].node.list_channels().is_empty());
5498         check_closed_broadcast!(nodes[0]);
5499 }
5500
5501 #[test]
5502 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
5503         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
5504         //    * 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.
5505
5506         let mut nodes = create_network(3, &[None, None, None]);
5507         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, LocalFeatures::new(), LocalFeatures::new());
5508         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, LocalFeatures::new(), LocalFeatures::new());
5509
5510         let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
5511         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5512
5513         //First hop
5514         let mut payment_event = {
5515                 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5516                 check_added_monitors!(nodes[0], 1);
5517                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5518                 assert_eq!(events.len(), 1);
5519                 SendEvent::from_event(events.remove(0))
5520         };
5521         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
5522         check_added_monitors!(nodes[1], 0);
5523         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5524         expect_pending_htlcs_forwardable!(nodes[1]);
5525         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
5526         assert_eq!(events_2.len(), 1);
5527         check_added_monitors!(nodes[1], 1);
5528         payment_event = SendEvent::from_event(events_2.remove(0));
5529         assert_eq!(payment_event.msgs.len(), 1);
5530
5531         //Second Hop
5532         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
5533         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
5534         check_added_monitors!(nodes[2], 0);
5535         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
5536
5537         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
5538         assert_eq!(events_3.len(), 1);
5539         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
5540                 match events_3[0] {
5541                         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 } } => {
5542                                 assert!(update_add_htlcs.is_empty());
5543                                 assert!(update_fulfill_htlcs.is_empty());
5544                                 assert!(update_fail_htlcs.is_empty());
5545                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
5546                                 assert!(update_fee.is_none());
5547                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
5548                         },
5549                         _ => panic!("Unexpected event"),
5550                 }
5551         };
5552
5553         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0).unwrap();
5554
5555         check_added_monitors!(nodes[1], 0);
5556         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
5557         expect_pending_htlcs_forwardable!(nodes[1]);
5558         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
5559         assert_eq!(events_4.len(), 1);
5560
5561         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
5562         match events_4[0] {
5563                 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, .. } } => {
5564                         assert!(update_add_htlcs.is_empty());
5565                         assert!(update_fulfill_htlcs.is_empty());
5566                         assert_eq!(update_fail_htlcs.len(), 1);
5567                         assert!(update_fail_malformed_htlcs.is_empty());
5568                         assert!(update_fee.is_none());
5569                 },
5570                 _ => panic!("Unexpected event"),
5571         };
5572
5573         check_added_monitors!(nodes[1], 1);
5574 }
5575
5576 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
5577         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
5578         // 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
5579         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
5580
5581         let nodes = create_network(2, &[None, None]);
5582         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
5583
5584         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
5585
5586         // We route 2 dust-HTLCs between A and B
5587         let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
5588         let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
5589         route_payment(&nodes[0], &[&nodes[1]], 1000000);
5590
5591         // Cache one local commitment tx as previous
5592         let as_prev_commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
5593
5594         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
5595         assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2));
5596         check_added_monitors!(nodes[1], 0);
5597         expect_pending_htlcs_forwardable!(nodes[1]);
5598         check_added_monitors!(nodes[1], 1);
5599
5600         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5601         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]).unwrap();
5602         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed).unwrap();
5603         check_added_monitors!(nodes[0], 1);
5604
5605         // Cache one local commitment tx as lastest
5606         let as_last_commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
5607
5608         let events = nodes[0].node.get_and_clear_pending_msg_events();
5609         match events[0] {
5610                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
5611                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
5612                 },
5613                 _ => panic!("Unexpected event"),
5614         }
5615         match events[1] {
5616                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
5617                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
5618                 },
5619                 _ => panic!("Unexpected event"),
5620         }
5621
5622         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
5623         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
5624         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5625         if announce_latest {
5626                 nodes[0].chain_monitor.block_connected_checked(&header, 1, &[&as_last_commitment_tx[0]], &[1; 1]);
5627         } else {
5628                 nodes[0].chain_monitor.block_connected_checked(&header, 1, &[&as_prev_commitment_tx[0]], &[1; 1]);
5629         }
5630
5631         let events = nodes[0].node.get_and_clear_pending_msg_events();
5632         assert_eq!(events.len(), 1);
5633         match events[0] {
5634                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5635                 _ => panic!("Unexpected event"),
5636         }
5637
5638         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
5639         connect_blocks(&nodes[0].chain_monitor, ANTI_REORG_DELAY - 1, 1, true,  header.bitcoin_hash());
5640         let events = nodes[0].node.get_and_clear_pending_events();
5641         // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
5642         assert_eq!(events.len(), 2);
5643         let mut first_failed = false;
5644         for event in events {
5645                 match event {
5646                         Event::PaymentFailed { payment_hash, .. } => {
5647                                 if payment_hash == payment_hash_1 {
5648                                         assert!(!first_failed);
5649                                         first_failed = true;
5650                                 } else {
5651                                         assert_eq!(payment_hash, payment_hash_2);
5652                                 }
5653                         }
5654                         _ => panic!("Unexpected event"),
5655                 }
5656         }
5657 }
5658
5659 #[test]
5660 fn test_failure_delay_dust_htlc_local_commitment() {
5661         do_test_failure_delay_dust_htlc_local_commitment(true);
5662         do_test_failure_delay_dust_htlc_local_commitment(false);
5663 }
5664
5665 #[test]
5666 fn test_no_failure_dust_htlc_local_commitment() {
5667         // Transaction filters for failing back dust htlc based on local commitment txn infos has been
5668         // prone to error, we test here that a dummy transaction don't fail them.
5669
5670         let nodes = create_network(2, &[None, None]);
5671         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
5672
5673         // Rebalance a bit
5674         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5675
5676         let as_dust_limit = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
5677         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
5678
5679         // We route 2 dust-HTLCs between A and B
5680         let (preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
5681         let (preimage_2, _) = route_payment(&nodes[1], &[&nodes[0]], as_dust_limit*1000);
5682
5683         // Build a dummy invalid transaction trying to spend a commitment tx
5684         let input = TxIn {
5685                 previous_output: BitcoinOutPoint { txid: chan.3.txid(), vout: 0 },
5686                 script_sig: Script::new(),
5687                 sequence: 0,
5688                 witness: Vec::new(),
5689         };
5690
5691         let outp = TxOut {
5692                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
5693                 value: 10000,
5694         };
5695
5696         let dummy_tx = Transaction {
5697                 version: 2,
5698                 lock_time: 0,
5699                 input: vec![input],
5700                 output: vec![outp]
5701         };
5702
5703         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5704         nodes[0].chan_monitor.simple_monitor.block_connected(&header, 1, &[&dummy_tx], &[1;1]);
5705         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
5706         assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
5707         // We broadcast a few more block to check everything is all right
5708         connect_blocks(&nodes[0].chain_monitor, 20, 1, true,  header.bitcoin_hash());
5709         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
5710         assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
5711
5712         claim_payment(&nodes[0], &vec!(&nodes[1])[..], preimage_1);
5713         claim_payment(&nodes[1], &vec!(&nodes[0])[..], preimage_2);
5714 }
5715
5716 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
5717         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
5718         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
5719         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
5720         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
5721         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
5722         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
5723
5724         let nodes = create_network(3, &[None, None, None]);
5725         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
5726
5727         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
5728
5729         let (_payment_preimage_1, dust_hash) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
5730         let (_payment_preimage_2, non_dust_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
5731
5732         let as_commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
5733         let bs_commitment_tx = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
5734
5735         // We revoked bs_commitment_tx
5736         if revoked {
5737                 let (payment_preimage_3, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
5738                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
5739         }
5740
5741         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5742         let mut timeout_tx = Vec::new();
5743         if local {
5744                 // We fail dust-HTLC 1 by broadcast of local commitment tx
5745                 nodes[0].chain_monitor.block_connected_checked(&header, 1, &[&as_commitment_tx[0]], &[1; 1]);
5746                 let events = nodes[0].node.get_and_clear_pending_msg_events();
5747                 assert_eq!(events.len(), 1);
5748                 match events[0] {
5749                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5750                         _ => panic!("Unexpected event"),
5751                 }
5752                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
5753                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
5754                 let parent_hash  = connect_blocks(&nodes[0].chain_monitor, ANTI_REORG_DELAY - 1, 2, true, header.bitcoin_hash());
5755                 let events = nodes[0].node.get_and_clear_pending_events();
5756                 assert_eq!(events.len(), 1);
5757                 match events[0] {
5758                         Event::PaymentFailed { payment_hash, .. } => {
5759                                 assert_eq!(payment_hash, dust_hash);
5760                         },
5761                         _ => panic!("Unexpected event"),
5762                 }
5763                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5764                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
5765                 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5766                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
5767                 nodes[0].chain_monitor.block_connected_checked(&header_2, 7, &[&timeout_tx[0]], &[1; 1]);
5768                 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5769                 connect_blocks(&nodes[0].chain_monitor, ANTI_REORG_DELAY - 1, 8, true, header_3.bitcoin_hash());
5770                 let events = nodes[0].node.get_and_clear_pending_events();
5771                 assert_eq!(events.len(), 1);
5772                 match events[0] {
5773                         Event::PaymentFailed { payment_hash, .. } => {
5774                                 assert_eq!(payment_hash, non_dust_hash);
5775                         },
5776                         _ => panic!("Unexpected event"),
5777                 }
5778         } else {
5779                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
5780                 nodes[0].chain_monitor.block_connected_checked(&header, 1, &[&bs_commitment_tx[0]], &[1; 1]);
5781                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
5782                 let events = nodes[0].node.get_and_clear_pending_msg_events();
5783                 assert_eq!(events.len(), 1);
5784                 match events[0] {
5785                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5786                         _ => panic!("Unexpected event"),
5787                 }
5788                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
5789                 let parent_hash  = connect_blocks(&nodes[0].chain_monitor, ANTI_REORG_DELAY - 1, 2, true, header.bitcoin_hash());
5790                 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5791                 if !revoked {
5792                         let events = nodes[0].node.get_and_clear_pending_events();
5793                         assert_eq!(events.len(), 1);
5794                         match events[0] {
5795                                 Event::PaymentFailed { payment_hash, .. } => {
5796                                         assert_eq!(payment_hash, dust_hash);
5797                                 },
5798                                 _ => panic!("Unexpected event"),
5799                         }
5800                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5801                         // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
5802                         nodes[0].chain_monitor.block_connected_checked(&header_2, 7, &[&timeout_tx[0]], &[1; 1]);
5803                         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
5804                         let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5805                         connect_blocks(&nodes[0].chain_monitor, ANTI_REORG_DELAY - 1, 8, true, header_3.bitcoin_hash());
5806                         let events = nodes[0].node.get_and_clear_pending_events();
5807                         assert_eq!(events.len(), 1);
5808                         match events[0] {
5809                                 Event::PaymentFailed { payment_hash, .. } => {
5810                                         assert_eq!(payment_hash, non_dust_hash);
5811                                 },
5812                                 _ => panic!("Unexpected event"),
5813                         }
5814                 } else {
5815                         // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
5816                         // commitment tx
5817                         let events = nodes[0].node.get_and_clear_pending_events();
5818                         assert_eq!(events.len(), 2);
5819                         let first;
5820                         match events[0] {
5821                                 Event::PaymentFailed { payment_hash, .. } => {
5822                                         if payment_hash == dust_hash { first = true; }
5823                                         else { first = false; }
5824                                 },
5825                                 _ => panic!("Unexpected event"),
5826                         }
5827                         match events[1] {
5828                                 Event::PaymentFailed { payment_hash, .. } => {
5829                                         if first { assert_eq!(payment_hash, non_dust_hash); }
5830                                         else { assert_eq!(payment_hash, dust_hash); }
5831                                 },
5832                                 _ => panic!("Unexpected event"),
5833                         }
5834                 }
5835         }
5836 }
5837
5838 #[test]
5839 fn test_sweep_outbound_htlc_failure_update() {
5840         do_test_sweep_outbound_htlc_failure_update(false, true);
5841         do_test_sweep_outbound_htlc_failure_update(false, false);
5842         do_test_sweep_outbound_htlc_failure_update(true, false);
5843 }
5844
5845 #[test]
5846 fn test_upfront_shutdown_script() {
5847         // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
5848         // enforce it at shutdown message
5849
5850         let mut config = UserConfig::new();
5851         config.channel_options.announced_channel = true;
5852         config.peer_channel_config_limits.force_announced_channel_preference = false;
5853         config.channel_options.commit_upfront_shutdown_pubkey = false;
5854         let nodes = create_network(3, &[None, Some(config), None]);
5855
5856         // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
5857         let flags = LocalFeatures::new();
5858         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
5859         nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
5860         let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
5861         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
5862         // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that  we disconnect peer
5863         if let Err(error) = nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown) {
5864                 if let Some(error) = error.action {
5865                         match error {
5866                                 ErrorAction::SendErrorMessage { msg } => {
5867                                         assert_eq!(msg.data,"Got shutdown request with a scriptpubkey which did not match their previous scriptpubkey");
5868                                 },
5869                                 _ => { assert!(false); }
5870                         }
5871                 } else { assert!(false); }
5872         } else { assert!(false); }
5873         let events = nodes[2].node.get_and_clear_pending_msg_events();
5874         assert_eq!(events.len(), 1);
5875         match events[0] {
5876                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5877                 _ => panic!("Unexpected event"),
5878         }
5879
5880         // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
5881         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
5882         nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
5883         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
5884         // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
5885         if let Ok(_) = nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown) {}
5886         else { assert!(false) }
5887         let events = nodes[2].node.get_and_clear_pending_msg_events();
5888         assert_eq!(events.len(), 1);
5889         match events[0] {
5890                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
5891                 _ => panic!("Unexpected event"),
5892         }
5893
5894         // We test that if case of peer non-signaling we don't enforce committed script at channel opening
5895         let mut flags_no = LocalFeatures::new();
5896         flags_no.unset_upfront_shutdown_script();
5897         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone());
5898         nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
5899         let mut node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5900         node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
5901         if let Ok(_) = nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_1_shutdown) {}
5902         else { assert!(false) }
5903         let events = nodes[1].node.get_and_clear_pending_msg_events();
5904         assert_eq!(events.len(), 1);
5905         match events[0] {
5906                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
5907                 _ => panic!("Unexpected event"),
5908         }
5909
5910         // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
5911         // channel smoothly, opt-out is from channel initiator here
5912         let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone());
5913         nodes[1].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
5914         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5915         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
5916         if let Ok(_) = nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown) {}
5917         else { assert!(false) }
5918         let events = nodes[0].node.get_and_clear_pending_msg_events();
5919         assert_eq!(events.len(), 1);
5920         match events[0] {
5921                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
5922                 _ => panic!("Unexpected event"),
5923         }
5924
5925         //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
5926         //// channel smoothly
5927         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone());
5928         nodes[1].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
5929         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5930         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
5931         if let Ok(_) = nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown) {}
5932         else { assert!(false) }
5933         let events = nodes[0].node.get_and_clear_pending_msg_events();
5934         assert_eq!(events.len(), 2);
5935         match events[0] {
5936                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
5937                 _ => panic!("Unexpected event"),
5938         }
5939         match events[1] {
5940                 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
5941                 _ => panic!("Unexpected event"),
5942         }
5943 }
5944
5945 #[test]
5946 fn test_user_configurable_csv_delay() {
5947         // We test our channel constructors yield errors when we pass them absurd csv delay
5948
5949         let mut low_our_to_self_config = UserConfig::new();
5950         low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
5951         let mut high_their_to_self_config = UserConfig::new();
5952         high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
5953         let nodes = create_network(2, &[Some(high_their_to_self_config.clone()), None]);
5954
5955         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
5956         let keys_manager: Arc<KeysInterface> = Arc::new(KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new()), 10, 20));
5957         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, Arc::new(test_utils::TestLogger::new()), &low_our_to_self_config) {
5958                 match error {
5959                         APIError::APIMisuseError { err } => { assert_eq!(err, "Configured with an unreasonable our_to_self_delay putting user funds at risks"); },
5960                         _ => panic!("Unexpected event"),
5961                 }
5962         } else { assert!(false) }
5963
5964         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
5965         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42).unwrap();
5966         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
5967         open_channel.to_self_delay = 200;
5968         if let Err(error) = Channel::new_from_req(&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &keys_manager, nodes[1].node.get_our_node_id(), LocalFeatures::new(), &open_channel, 0, Arc::new(test_utils::TestLogger::new()), &low_our_to_self_config) {
5969                 match error {
5970                         ChannelError::Close(err) => { assert_eq!(err, "Configured with an unreasonable our_to_self_delay putting user funds at risks"); },
5971                         _ => panic!("Unexpected event"),
5972                 }
5973         } else { assert!(false); }
5974
5975         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
5976         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42).unwrap();
5977         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), LocalFeatures::new(), &get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id())).unwrap();
5978         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5979         accept_channel.to_self_delay = 200;
5980         if let Err(error) = nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), LocalFeatures::new(), &accept_channel) {
5981                 if let Some(error) = error.action {
5982                         match error {
5983                                 ErrorAction::SendErrorMessage { msg } => {
5984                                         assert_eq!(msg.data,"They wanted our payments to be delayed by a needlessly long period");
5985                                 },
5986                                 _ => { assert!(false); }
5987                         }
5988                 } else { assert!(false); }
5989         } else { assert!(false); }
5990
5991         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
5992         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42).unwrap();
5993         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
5994         open_channel.to_self_delay = 200;
5995         if let Err(error) = Channel::new_from_req(&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &keys_manager, nodes[1].node.get_our_node_id(), LocalFeatures::new(), &open_channel, 0, Arc::new(test_utils::TestLogger::new()), &high_their_to_self_config) {
5996                 match error {
5997                         ChannelError::Close(err) => { assert_eq!(err, "They wanted our payments to be delayed by a needlessly long period"); },
5998                         _ => panic!("Unexpected event"),
5999                 }
6000         } else { assert!(false); }
6001 }
6002
6003 #[test]
6004 fn test_data_loss_protect() {
6005         // We want to be sure that :
6006         // * we don't broadcast our Local Commitment Tx in case of fallen behind
6007         // * we close channel in case of detecting other being fallen behind
6008         // * we are able to claim our own outputs thanks to remote my_current_per_commitment_point
6009         let mut nodes = create_network(2, &[None, None]);
6010
6011         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, LocalFeatures::new(), LocalFeatures::new());
6012
6013         // Cache node A state before any channel update
6014         let previous_node_state = nodes[0].node.encode();
6015         let mut previous_chan_monitor_state = test_utils::TestVecWriter(Vec::new());
6016         nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut previous_chan_monitor_state).unwrap();
6017
6018         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
6019         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
6020
6021         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6022         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6023
6024         // Restore node A from previous state
6025         let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::with_id(format!("node {}", 0)));
6026         let chan_monitor = <(Sha256dHash, ChannelMonitor)>::read(&mut ::std::io::Cursor::new(previous_chan_monitor_state.0), Arc::clone(&logger)).unwrap().1;
6027         let chain_monitor = Arc::new(ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
6028         let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())});
6029         let feeest = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 });
6030         let monitor = Arc::new(test_utils::TestChannelMonitor::new(chain_monitor.clone(), tx_broadcaster.clone(), logger.clone(), feeest.clone()));
6031         let mut channel_monitors = HashMap::new();
6032         channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &chan_monitor);
6033         let node_state_0 = <(Sha256dHash, ChannelManager)>::read(&mut ::std::io::Cursor::new(previous_node_state), ChannelManagerReadArgs {
6034                 keys_manager: Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::clone(&logger), 42, 21)),
6035                 fee_estimator: feeest.clone(),
6036                 monitor: monitor.clone(),
6037                 chain_monitor: chain_monitor.clone(),
6038                 logger: Arc::clone(&logger),
6039                 tx_broadcaster,
6040                 default_config: UserConfig::new(),
6041                 channel_monitors: &channel_monitors
6042         }).unwrap().1;
6043         nodes[0].node = Arc::new(node_state_0);
6044         monitor.add_update_monitor(OutPoint { txid: chan.3.txid(), index: 0 }, chan_monitor.clone()).is_ok();
6045         nodes[0].chan_monitor = monitor;
6046         nodes[0].chain_monitor = chain_monitor;
6047         check_added_monitors!(nodes[0], 1);
6048
6049         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
6050         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
6051
6052         let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6053
6054         // Check we update monitor following learning of per_commitment_point from B
6055         if let Err(err) = nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0])  {
6056                 if let Some(error) = err.action {
6057                         match error {
6058                                 ErrorAction::SendErrorMessage { msg } => {
6059                                         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");
6060                                 },
6061                                 _ => panic!("Unexpected event!"),
6062                         }
6063                 } else { assert!(false); }
6064         } else { assert!(false); }
6065         check_added_monitors!(nodes[0], 1);
6066
6067         {
6068                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
6069                 assert_eq!(node_txn.len(), 0);
6070         }
6071
6072         let mut reestablish_1 = Vec::with_capacity(1);
6073         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
6074                 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
6075                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
6076                         reestablish_1.push(msg.clone());
6077                 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
6078                 } else {
6079                         panic!("Unexpected event")
6080                 }
6081         }
6082
6083         // Check we close channel detecting A is fallen-behind
6084         if let Err(err) = nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]) {
6085                 if let Some(error) = err.action {
6086                         match error {
6087                                 ErrorAction::SendErrorMessage { msg } => {
6088                                         assert_eq!(msg.data, "Peer attempted to reestablish channel with a very old local commitment transaction"); },
6089                                 _ => panic!("Unexpected event!"),
6090                         }
6091                 } else { assert!(false); }
6092         } else { assert!(false); }
6093
6094         let events = nodes[1].node.get_and_clear_pending_msg_events();
6095         assert_eq!(events.len(), 1);
6096         match events[0] {
6097                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6098                 _ => panic!("Unexpected event"),
6099         }
6100
6101         // Check A is able to claim to_remote output
6102         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
6103         assert_eq!(node_txn.len(), 1);
6104         check_spends!(node_txn[0], chan.3.clone());
6105         assert_eq!(node_txn[0].output.len(), 2);
6106         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6107         nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()]}, 1);
6108         let spend_txn = check_spendable_outputs!(nodes[0], 1);
6109         assert_eq!(spend_txn.len(), 1);
6110         check_spends!(spend_txn[0], node_txn[0].clone());
6111 }