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