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