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