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