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