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