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