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