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