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