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