Split routing from getting network messages
[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::keysinterface::{ChannelKeys, KeysInterface, SpendableOutputDescriptor};
7 use chain::chaininterface;
8 use chain::chaininterface::{ChainListener, ChainWatchInterfaceUtil, BlockNotifier};
9 use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
10 use ln::channelmanager::{ChannelManager,ChannelManagerReadArgs,HTLCForwardInfo,RAACommitmentOrder, PaymentPreimage, PaymentHash, PaymentSecret, PaymentSendFailure, BREAKDOWN_TIMEOUT};
11 use ln::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ManyChannelMonitor, ANTI_REORG_DELAY};
12 use ln::channelmonitor;
13 use ln::channel::{Channel, ChannelError};
14 use ln::{chan_utils, onion_utils};
15 use routing::router::{Route, RouteHop, get_route};
16 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
17 use ln::msgs;
18 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler,HTLCFailChannelUpdate, ErrorAction};
19 use util::enforcing_trait_impls::EnforcingChannelKeys;
20 use util::{byte_utils, test_utils};
21 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
22 use util::errors::APIError;
23 use util::ser::{Writeable, Writer, ReadableArgs};
24 use util::config::UserConfig;
25 use util::logger::Logger;
26
27 use bitcoin::util::hash::BitcoinHash;
28 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
29 use bitcoin::hash_types::{Txid, BlockHash};
30 use bitcoin::util::bip143;
31 use bitcoin::util::address::Address;
32 use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
33 use bitcoin::blockdata::block::{Block, BlockHeader};
34 use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType, OutPoint as BitcoinOutPoint};
35 use bitcoin::blockdata::script::{Builder, Script};
36 use bitcoin::blockdata::opcodes;
37 use bitcoin::blockdata::constants::genesis_block;
38 use bitcoin::network::constants::Network;
39
40 use bitcoin::hashes::sha256::Hash as Sha256;
41 use bitcoin::hashes::Hash;
42
43 use bitcoin::secp256k1::{Secp256k1, Message};
44 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
45
46 use std::collections::{BTreeSet, HashMap, HashSet};
47 use std::default::Default;
48 use std::sync::{Arc, Mutex};
49 use std::sync::atomic::Ordering;
50 use std::{mem, io};
51
52 use rand::{thread_rng, Rng};
53
54 use ln::functional_test_utils::*;
55
56 #[test]
57 fn test_insane_channel_opens() {
58         // Stand up a network of 2 nodes
59         let chanmon_cfgs = create_chanmon_cfgs(2);
60         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
61         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
62         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
63
64         // Instantiate channel parameters where we push the maximum msats given our
65         // funding satoshis
66         let channel_value_sat = 31337; // same as funding satoshis
67         let channel_reserve_satoshis = Channel::<EnforcingChannelKeys>::get_remote_channel_reserve_satoshis(channel_value_sat);
68         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
69
70         // Have node0 initiate a channel to node1 with aforementioned parameters
71         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
72
73         // Extract the channel open message from node0 to node1
74         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
75
76         // Test helper that asserts we get the correct error string given a mutator
77         // that supposedly makes the channel open message insane
78         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
79                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
80                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
81                 assert_eq!(msg_events.len(), 1);
82                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
83                         match action {
84                                 &ErrorAction::SendErrorMessage { .. } => {
85                                         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), expected_error_str.to_string(), 1);
86                                 },
87                                 _ => panic!("unexpected event!"),
88                         }
89                 } else { assert!(false); }
90         };
91
92         use ln::channel::MAX_FUNDING_SATOSHIS;
93         use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
94
95         // Test all mutations that would make the channel open message insane
96         insane_open_helper("funding value > 2^24", |mut msg| { msg.funding_satoshis = MAX_FUNDING_SATOSHIS; msg });
97
98         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
99
100         insane_open_helper("push_msat larger than funding value", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
101
102         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
103
104         insane_open_helper("Bogus; channel reserve is less than dust limit", |mut msg| { msg.dust_limit_satoshis = msg.channel_reserve_satoshis + 1; msg });
105
106         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 });
107
108         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 });
109
110         insane_open_helper("0 max_accpted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
111
112         insane_open_helper("max_accpted_htlcs > 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
113 }
114
115 #[test]
116 fn test_async_inbound_update_fee() {
117         let chanmon_cfgs = create_chanmon_cfgs(2);
118         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
119         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
120         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
121         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
122         let logger = Arc::new(test_utils::TestLogger::new());
123         let channel_id = chan.2;
124
125         // balancing
126         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
127
128         // A                                        B
129         // update_fee                            ->
130         // send (1) commitment_signed            -.
131         //                                       <- update_add_htlc/commitment_signed
132         // send (2) RAA (awaiting remote revoke) -.
133         // (1) commitment_signed is delivered    ->
134         //                                       .- send (3) RAA (awaiting remote revoke)
135         // (2) RAA is delivered                  ->
136         //                                       .- send (4) commitment_signed
137         //                                       <- (3) RAA is delivered
138         // send (5) commitment_signed            -.
139         //                                       <- (4) commitment_signed is delivered
140         // send (6) RAA                          -.
141         // (5) commitment_signed is delivered    ->
142         //                                       <- RAA
143         // (6) RAA is delivered                  ->
144
145         // First nodes[0] generates an update_fee
146         nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
147         check_added_monitors!(nodes[0], 1);
148
149         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
150         assert_eq!(events_0.len(), 1);
151         let (update_msg, commitment_signed) = match events_0[0] { // (1)
152                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
153                         (update_fee.as_ref(), commitment_signed)
154                 },
155                 _ => panic!("Unexpected event"),
156         };
157
158         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
159
160         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
161         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
162         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
163         nodes[1].node.send_payment(&get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[0].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV, logger.clone()).unwrap(), our_payment_hash, &None).unwrap();
164         check_added_monitors!(nodes[1], 1);
165
166         let payment_event = {
167                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
168                 assert_eq!(events_1.len(), 1);
169                 SendEvent::from_event(events_1.remove(0))
170         };
171         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
172         assert_eq!(payment_event.msgs.len(), 1);
173
174         // ...now when the messages get delivered everyone should be happy
175         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
176         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
177         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
178         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
179         check_added_monitors!(nodes[0], 1);
180
181         // deliver(1), generate (3):
182         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
183         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
184         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
185         check_added_monitors!(nodes[1], 1);
186
187         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
188         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
189         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
190         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
191         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
192         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
193         assert!(bs_update.update_fee.is_none()); // (4)
194         check_added_monitors!(nodes[1], 1);
195
196         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
197         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
198         assert!(as_update.update_add_htlcs.is_empty()); // (5)
199         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
200         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
201         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
202         assert!(as_update.update_fee.is_none()); // (5)
203         check_added_monitors!(nodes[0], 1);
204
205         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
206         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
207         // only (6) so get_event_msg's assert(len == 1) passes
208         check_added_monitors!(nodes[0], 1);
209
210         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
211         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
212         check_added_monitors!(nodes[1], 1);
213
214         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
215         check_added_monitors!(nodes[0], 1);
216
217         let events_2 = nodes[0].node.get_and_clear_pending_events();
218         assert_eq!(events_2.len(), 1);
219         match events_2[0] {
220                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
221                 _ => panic!("Unexpected event"),
222         }
223
224         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
225         check_added_monitors!(nodes[1], 1);
226 }
227
228 #[test]
229 fn test_update_fee_unordered_raa() {
230         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
231         // crash in an earlier version of the update_fee patch)
232         let chanmon_cfgs = create_chanmon_cfgs(2);
233         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
234         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
235         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
236         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
237         let channel_id = chan.2;
238         let logger = Arc::new(test_utils::TestLogger::new());
239
240         // balancing
241         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
242
243         // First nodes[0] generates an update_fee
244         nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
245         check_added_monitors!(nodes[0], 1);
246
247         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
248         assert_eq!(events_0.len(), 1);
249         let update_msg = match events_0[0] { // (1)
250                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
251                         update_fee.as_ref()
252                 },
253                 _ => panic!("Unexpected event"),
254         };
255
256         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
257
258         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
259         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
260         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
261         nodes[1].node.send_payment(&get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[0].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV, logger.clone()).unwrap(), our_payment_hash, &None).unwrap();
262         check_added_monitors!(nodes[1], 1);
263
264         let payment_event = {
265                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
266                 assert_eq!(events_1.len(), 1);
267                 SendEvent::from_event(events_1.remove(0))
268         };
269         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
270         assert_eq!(payment_event.msgs.len(), 1);
271
272         // ...now when the messages get delivered everyone should be happy
273         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
274         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
275         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
276         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
277         check_added_monitors!(nodes[0], 1);
278
279         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
280         check_added_monitors!(nodes[1], 1);
281
282         // We can't continue, sadly, because our (1) now has a bogus signature
283 }
284
285 #[test]
286 fn test_multi_flight_update_fee() {
287         let chanmon_cfgs = create_chanmon_cfgs(2);
288         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
289         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
290         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
291         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
292         let channel_id = chan.2;
293
294         // A                                        B
295         // update_fee/commitment_signed          ->
296         //                                       .- send (1) RAA and (2) commitment_signed
297         // update_fee (never committed)          ->
298         // (3) update_fee                        ->
299         // We have to manually generate the above update_fee, it is allowed by the protocol but we
300         // don't track which updates correspond to which revoke_and_ack responses so we're in
301         // AwaitingRAA mode and will not generate the update_fee yet.
302         //                                       <- (1) RAA delivered
303         // (3) is generated and send (4) CS      -.
304         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
305         // know the per_commitment_point to use for it.
306         //                                       <- (2) commitment_signed delivered
307         // revoke_and_ack                        ->
308         //                                          B should send no response here
309         // (4) commitment_signed delivered       ->
310         //                                       <- RAA/commitment_signed delivered
311         // revoke_and_ack                        ->
312
313         // First nodes[0] generates an update_fee
314         let initial_feerate = get_feerate!(nodes[0], channel_id);
315         nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
316         check_added_monitors!(nodes[0], 1);
317
318         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
319         assert_eq!(events_0.len(), 1);
320         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
321                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
322                         (update_fee.as_ref().unwrap(), commitment_signed)
323                 },
324                 _ => panic!("Unexpected event"),
325         };
326
327         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
328         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
329         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
330         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
331         check_added_monitors!(nodes[1], 1);
332
333         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
334         // transaction:
335         nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
336         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
337         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
338
339         // Create the (3) update_fee message that nodes[0] will generate before it does...
340         let mut update_msg_2 = msgs::UpdateFee {
341                 channel_id: update_msg_1.channel_id.clone(),
342                 feerate_per_kw: (initial_feerate + 30) as u32,
343         };
344
345         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
346
347         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
348         // Deliver (3)
349         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
350
351         // Deliver (1), generating (3) and (4)
352         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
353         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
354         check_added_monitors!(nodes[0], 1);
355         assert!(as_second_update.update_add_htlcs.is_empty());
356         assert!(as_second_update.update_fulfill_htlcs.is_empty());
357         assert!(as_second_update.update_fail_htlcs.is_empty());
358         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
359         // Check that the update_fee newly generated matches what we delivered:
360         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
361         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
362
363         // Deliver (2) commitment_signed
364         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
365         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
366         check_added_monitors!(nodes[0], 1);
367         // No commitment_signed so get_event_msg's assert(len == 1) passes
368
369         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
370         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
371         check_added_monitors!(nodes[1], 1);
372
373         // Delever (4)
374         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
375         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
376         check_added_monitors!(nodes[1], 1);
377
378         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
379         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
380         check_added_monitors!(nodes[0], 1);
381
382         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
383         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
384         // No commitment_signed so get_event_msg's assert(len == 1) passes
385         check_added_monitors!(nodes[0], 1);
386
387         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
388         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
389         check_added_monitors!(nodes[1], 1);
390 }
391
392 #[test]
393 fn test_1_conf_open() {
394         // Previously, if the minium_depth config was set to 1, we'd never send a funding_locked. This
395         // tests that we properly send one in that case.
396         let mut alice_config = UserConfig::default();
397         alice_config.own_channel_config.minimum_depth = 1;
398         alice_config.channel_options.announced_channel = true;
399         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
400         let mut bob_config = UserConfig::default();
401         bob_config.own_channel_config.minimum_depth = 1;
402         bob_config.channel_options.announced_channel = true;
403         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
404         let chanmon_cfgs = create_chanmon_cfgs(2);
405         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
406         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(alice_config), Some(bob_config)]);
407         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
408
409         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
410         assert!(nodes[0].chain_monitor.does_match_tx(&tx));
411         assert!(nodes[1].chain_monitor.does_match_tx(&tx));
412
413         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
414         nodes[1].block_notifier.block_connected_checked(&header, 1, &[&tx; 1], &[tx.version; 1]);
415         nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendFundingLocked, nodes[0].node.get_our_node_id()));
416
417         nodes[0].block_notifier.block_connected_checked(&header, 1, &[&tx; 1], &[tx.version; 1]);
418         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
419         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
420
421         for node in nodes {
422                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
423                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
424                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
425         }
426 }
427
428 fn do_test_sanity_on_in_flight_opens(steps: u8) {
429         // Previously, we had issues deserializing channels when we hadn't connected the first block
430         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
431         // serialization round-trips and simply do steps towards opening a channel and then drop the
432         // Node objects.
433
434         let chanmon_cfgs = create_chanmon_cfgs(2);
435         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
436         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
437         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
438
439         if steps & 0b1000_0000 != 0{
440                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
441                 nodes[0].block_notifier.block_connected_checked(&header, 1, &Vec::new(), &[0; 0]);
442                 nodes[1].block_notifier.block_connected_checked(&header, 1, &Vec::new(), &[0; 0]);
443         }
444
445         if steps & 0x0f == 0 { return; }
446         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
447         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
448
449         if steps & 0x0f == 1 { return; }
450         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
451         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
452
453         if steps & 0x0f == 2 { return; }
454         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
455
456         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
457
458         if steps & 0x0f == 3 { return; }
459         nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
460         check_added_monitors!(nodes[0], 0);
461         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
462
463         if steps & 0x0f == 4 { return; }
464         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
465         {
466                 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
467                 assert_eq!(added_monitors.len(), 1);
468                 assert_eq!(added_monitors[0].0, funding_output);
469                 added_monitors.clear();
470         }
471         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
472
473         if steps & 0x0f == 5 { return; }
474         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
475         {
476                 let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
477                 assert_eq!(added_monitors.len(), 1);
478                 assert_eq!(added_monitors[0].0, funding_output);
479                 added_monitors.clear();
480         }
481
482         let events_4 = nodes[0].node.get_and_clear_pending_events();
483         assert_eq!(events_4.len(), 1);
484         match events_4[0] {
485                 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
486                         assert_eq!(user_channel_id, 42);
487                         assert_eq!(*funding_txo, funding_output);
488                 },
489                 _ => panic!("Unexpected event"),
490         };
491
492         if steps & 0x0f == 6 { return; }
493         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx);
494
495         if steps & 0x0f == 7 { return; }
496         confirm_transaction(&nodes[0].block_notifier, &nodes[0].chain_monitor, &tx, tx.version);
497         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
498 }
499
500 #[test]
501 fn test_sanity_on_in_flight_opens() {
502         do_test_sanity_on_in_flight_opens(0);
503         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
504         do_test_sanity_on_in_flight_opens(1);
505         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
506         do_test_sanity_on_in_flight_opens(2);
507         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
508         do_test_sanity_on_in_flight_opens(3);
509         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
510         do_test_sanity_on_in_flight_opens(4);
511         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
512         do_test_sanity_on_in_flight_opens(5);
513         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
514         do_test_sanity_on_in_flight_opens(6);
515         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
516         do_test_sanity_on_in_flight_opens(7);
517         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
518         do_test_sanity_on_in_flight_opens(8);
519         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
520 }
521
522 #[test]
523 fn test_update_fee_vanilla() {
524         let chanmon_cfgs = create_chanmon_cfgs(2);
525         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
526         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
527         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
528         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
529         let channel_id = chan.2;
530
531         let feerate = get_feerate!(nodes[0], channel_id);
532         nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
533         check_added_monitors!(nodes[0], 1);
534
535         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
536         assert_eq!(events_0.len(), 1);
537         let (update_msg, commitment_signed) = match events_0[0] {
538                         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 } } => {
539                         (update_fee.as_ref(), commitment_signed)
540                 },
541                 _ => panic!("Unexpected event"),
542         };
543         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
544
545         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
546         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
547         check_added_monitors!(nodes[1], 1);
548
549         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
550         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
551         check_added_monitors!(nodes[0], 1);
552
553         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
554         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
555         // No commitment_signed so get_event_msg's assert(len == 1) passes
556         check_added_monitors!(nodes[0], 1);
557
558         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
559         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
560         check_added_monitors!(nodes[1], 1);
561 }
562
563 #[test]
564 fn test_update_fee_that_funder_cannot_afford() {
565         let chanmon_cfgs = create_chanmon_cfgs(2);
566         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
567         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
568         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
569         let channel_value = 1888;
570         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000, InitFeatures::known(), InitFeatures::known());
571         let channel_id = chan.2;
572
573         let feerate = 260;
574         nodes[0].node.update_fee(channel_id, feerate).unwrap();
575         check_added_monitors!(nodes[0], 1);
576         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
577
578         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
579
580         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
581
582         //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
583         //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
584         {
585                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
586
587                 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
588                 let num_htlcs = commitment_tx.output.len() - 2;
589                 let total_fee: u64 = feerate * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
590                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
591                 actual_fee = channel_value - actual_fee;
592                 assert_eq!(total_fee, actual_fee);
593         }
594
595         //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
596         //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
597         nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
598         check_added_monitors!(nodes[0], 1);
599
600         let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
601
602         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap());
603
604         //While producing the commitment_signed response after handling a received update_fee request the
605         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
606         //Should produce and error.
607         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed);
608         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
609         check_added_monitors!(nodes[1], 1);
610         check_closed_broadcast!(nodes[1], true);
611 }
612
613 #[test]
614 fn test_update_fee_with_fundee_update_add_htlc() {
615         let chanmon_cfgs = create_chanmon_cfgs(2);
616         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
617         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
618         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
619         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
620         let channel_id = chan.2;
621         let logger = Arc::new(test_utils::TestLogger::new());
622
623         // balancing
624         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
625
626         let feerate = get_feerate!(nodes[0], channel_id);
627         nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
628         check_added_monitors!(nodes[0], 1);
629
630         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
631         assert_eq!(events_0.len(), 1);
632         let (update_msg, commitment_signed) = match events_0[0] {
633                         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 } } => {
634                         (update_fee.as_ref(), commitment_signed)
635                 },
636                 _ => panic!("Unexpected event"),
637         };
638         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
639         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
640         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
641         check_added_monitors!(nodes[1], 1);
642
643         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
644         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
645         let route = get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[0].node.get_our_node_id(), None, &Vec::new(), 800000, TEST_FINAL_CLTV, logger.clone()).unwrap();
646
647         // nothing happens since node[1] is in AwaitingRemoteRevoke
648         nodes[1].node.send_payment(&route, our_payment_hash, &None).unwrap();
649         {
650                 let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
651                 assert_eq!(added_monitors.len(), 0);
652                 added_monitors.clear();
653         }
654         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
655         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
656         // node[1] has nothing to do
657
658         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
659         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
660         check_added_monitors!(nodes[0], 1);
661
662         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
663         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
664         // No commitment_signed so get_event_msg's assert(len == 1) passes
665         check_added_monitors!(nodes[0], 1);
666         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
667         check_added_monitors!(nodes[1], 1);
668         // AwaitingRemoteRevoke ends here
669
670         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
671         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
672         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
673         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
674         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
675         assert_eq!(commitment_update.update_fee.is_none(), true);
676
677         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
678         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
679         check_added_monitors!(nodes[0], 1);
680         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
681
682         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
683         check_added_monitors!(nodes[1], 1);
684         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
685
686         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
687         check_added_monitors!(nodes[1], 1);
688         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
689         // No commitment_signed so get_event_msg's assert(len == 1) passes
690
691         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
692         check_added_monitors!(nodes[0], 1);
693         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
694
695         expect_pending_htlcs_forwardable!(nodes[0]);
696
697         let events = nodes[0].node.get_and_clear_pending_events();
698         assert_eq!(events.len(), 1);
699         match events[0] {
700                 Event::PaymentReceived { .. } => { },
701                 _ => panic!("Unexpected event"),
702         };
703
704         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage, 800_000);
705
706         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000, 800_000);
707         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000, 800_000);
708         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
709 }
710
711 #[test]
712 fn test_update_fee() {
713         let chanmon_cfgs = create_chanmon_cfgs(2);
714         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
715         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
716         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
717         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
718         let channel_id = chan.2;
719
720         // A                                        B
721         // (1) update_fee/commitment_signed      ->
722         //                                       <- (2) revoke_and_ack
723         //                                       .- send (3) commitment_signed
724         // (4) update_fee/commitment_signed      ->
725         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
726         //                                       <- (3) commitment_signed delivered
727         // send (6) revoke_and_ack               -.
728         //                                       <- (5) deliver revoke_and_ack
729         // (6) deliver revoke_and_ack            ->
730         //                                       .- send (7) commitment_signed in response to (4)
731         //                                       <- (7) deliver commitment_signed
732         // revoke_and_ack                        ->
733
734         // Create and deliver (1)...
735         let feerate = get_feerate!(nodes[0], channel_id);
736         nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
737         check_added_monitors!(nodes[0], 1);
738
739         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
740         assert_eq!(events_0.len(), 1);
741         let (update_msg, commitment_signed) = match events_0[0] {
742                         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 } } => {
743                         (update_fee.as_ref(), commitment_signed)
744                 },
745                 _ => panic!("Unexpected event"),
746         };
747         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
748
749         // Generate (2) and (3):
750         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
751         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
752         check_added_monitors!(nodes[1], 1);
753
754         // Deliver (2):
755         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
756         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
757         check_added_monitors!(nodes[0], 1);
758
759         // Create and deliver (4)...
760         nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
761         check_added_monitors!(nodes[0], 1);
762         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
763         assert_eq!(events_0.len(), 1);
764         let (update_msg, commitment_signed) = match events_0[0] {
765                         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 } } => {
766                         (update_fee.as_ref(), commitment_signed)
767                 },
768                 _ => panic!("Unexpected event"),
769         };
770
771         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
772         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
773         check_added_monitors!(nodes[1], 1);
774         // ... creating (5)
775         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
776         // No commitment_signed so get_event_msg's assert(len == 1) passes
777
778         // Handle (3), creating (6):
779         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
780         check_added_monitors!(nodes[0], 1);
781         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
782         // No commitment_signed so get_event_msg's assert(len == 1) passes
783
784         // Deliver (5):
785         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
786         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
787         check_added_monitors!(nodes[0], 1);
788
789         // Deliver (6), creating (7):
790         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
791         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
792         assert!(commitment_update.update_add_htlcs.is_empty());
793         assert!(commitment_update.update_fulfill_htlcs.is_empty());
794         assert!(commitment_update.update_fail_htlcs.is_empty());
795         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
796         assert!(commitment_update.update_fee.is_none());
797         check_added_monitors!(nodes[1], 1);
798
799         // Deliver (7)
800         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
801         check_added_monitors!(nodes[0], 1);
802         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
803         // No commitment_signed so get_event_msg's assert(len == 1) passes
804
805         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
806         check_added_monitors!(nodes[1], 1);
807         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
808
809         assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
810         assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
811         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
812 }
813
814 #[test]
815 fn pre_funding_lock_shutdown_test() {
816         // Test sending a shutdown prior to funding_locked after funding generation
817         let chanmon_cfgs = create_chanmon_cfgs(2);
818         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
819         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
820         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
821         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0, InitFeatures::known(), InitFeatures::known());
822         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
823         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![tx.clone()]}, 1);
824         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![tx.clone()]}, 1);
825
826         nodes[0].node.close_channel(&OutPoint::new(tx.txid(), 0).to_channel_id()).unwrap();
827         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
828         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
829         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
830         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
831
832         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
833         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
834         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
835         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
836         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
837         assert!(node_0_none.is_none());
838
839         assert!(nodes[0].node.list_channels().is_empty());
840         assert!(nodes[1].node.list_channels().is_empty());
841 }
842
843 #[test]
844 fn updates_shutdown_wait() {
845         // Test sending a shutdown with outstanding updates pending
846         let chanmon_cfgs = create_chanmon_cfgs(3);
847         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
848         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
849         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
850         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
851         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
852         let logger = Arc::new(test_utils::TestLogger::new());
853
854         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
855
856         nodes[0].node.close_channel(&chan_1.2).unwrap();
857         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
858         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
859         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
860         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
861
862         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
863         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
864
865         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
866
867         let net_graph_msg_handler0 = &nodes[0].net_graph_msg_handler;
868         let net_graph_msg_handler1 = &nodes[1].net_graph_msg_handler;
869         let route_1 = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler0, &nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, logger.clone()).unwrap();
870         let route_2 = get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler1, &nodes[0].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, logger.clone()).unwrap();
871         unwrap_send_err!(nodes[0].node.send_payment(&route_1, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
872         unwrap_send_err!(nodes[1].node.send_payment(&route_2, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
873
874         assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
875         check_added_monitors!(nodes[2], 1);
876         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
877         assert!(updates.update_add_htlcs.is_empty());
878         assert!(updates.update_fail_htlcs.is_empty());
879         assert!(updates.update_fail_malformed_htlcs.is_empty());
880         assert!(updates.update_fee.is_none());
881         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
882         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
883         check_added_monitors!(nodes[1], 1);
884         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
885         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
886
887         assert!(updates_2.update_add_htlcs.is_empty());
888         assert!(updates_2.update_fail_htlcs.is_empty());
889         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
890         assert!(updates_2.update_fee.is_none());
891         assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
892         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
893         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
894
895         let events = nodes[0].node.get_and_clear_pending_events();
896         assert_eq!(events.len(), 1);
897         match events[0] {
898                 Event::PaymentSent { ref payment_preimage } => {
899                         assert_eq!(our_payment_preimage, *payment_preimage);
900                 },
901                 _ => panic!("Unexpected event"),
902         }
903
904         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
905         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
906         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
907         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
908         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
909         assert!(node_0_none.is_none());
910
911         assert!(nodes[0].node.list_channels().is_empty());
912
913         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
914         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
915         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
916         assert!(nodes[1].node.list_channels().is_empty());
917         assert!(nodes[2].node.list_channels().is_empty());
918 }
919
920 #[test]
921 fn htlc_fail_async_shutdown() {
922         // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
923         let chanmon_cfgs = create_chanmon_cfgs(3);
924         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
925         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
926         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
927         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
928         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
929         let logger = Arc::new(test_utils::TestLogger::new());
930
931         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
932         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
933         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, logger.clone()).unwrap();
934         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
935         check_added_monitors!(nodes[0], 1);
936         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
937         assert_eq!(updates.update_add_htlcs.len(), 1);
938         assert!(updates.update_fulfill_htlcs.is_empty());
939         assert!(updates.update_fail_htlcs.is_empty());
940         assert!(updates.update_fail_malformed_htlcs.is_empty());
941         assert!(updates.update_fee.is_none());
942
943         nodes[1].node.close_channel(&chan_1.2).unwrap();
944         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
945         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
946         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
947
948         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
949         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
950         check_added_monitors!(nodes[1], 1);
951         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
952         commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
953
954         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
955         assert!(updates_2.update_add_htlcs.is_empty());
956         assert!(updates_2.update_fulfill_htlcs.is_empty());
957         assert_eq!(updates_2.update_fail_htlcs.len(), 1);
958         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
959         assert!(updates_2.update_fee.is_none());
960
961         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]);
962         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
963
964         expect_payment_failed!(nodes[0], our_payment_hash, false);
965
966         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
967         assert_eq!(msg_events.len(), 2);
968         let node_0_closing_signed = match msg_events[0] {
969                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
970                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
971                         (*msg).clone()
972                 },
973                 _ => panic!("Unexpected event"),
974         };
975         match msg_events[1] {
976                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
977                         assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
978                 },
979                 _ => panic!("Unexpected event"),
980         }
981
982         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
983         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
984         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
985         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
986         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
987         assert!(node_0_none.is_none());
988
989         assert!(nodes[0].node.list_channels().is_empty());
990
991         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
992         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
993         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
994         assert!(nodes[1].node.list_channels().is_empty());
995         assert!(nodes[2].node.list_channels().is_empty());
996 }
997
998 fn do_test_shutdown_rebroadcast(recv_count: u8) {
999         // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
1000         // messages delivered prior to disconnect
1001         let chanmon_cfgs = create_chanmon_cfgs(3);
1002         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1003         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1004         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1005         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1006         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1007
1008         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
1009
1010         nodes[1].node.close_channel(&chan_1.2).unwrap();
1011         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1012         if recv_count > 0 {
1013                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
1014                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1015                 if recv_count > 1 {
1016                         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
1017                 }
1018         }
1019
1020         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1021         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1022
1023         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1024         let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1025         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1026         let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1027
1028         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish);
1029         let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1030         assert!(node_1_shutdown == node_1_2nd_shutdown);
1031
1032         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish);
1033         let node_0_2nd_shutdown = if recv_count > 0 {
1034                 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1035                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
1036                 node_0_2nd_shutdown
1037         } else {
1038                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1039                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
1040                 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
1041         };
1042         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown);
1043
1044         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1045         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1046
1047         assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
1048         check_added_monitors!(nodes[2], 1);
1049         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1050         assert!(updates.update_add_htlcs.is_empty());
1051         assert!(updates.update_fail_htlcs.is_empty());
1052         assert!(updates.update_fail_malformed_htlcs.is_empty());
1053         assert!(updates.update_fee.is_none());
1054         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
1055         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
1056         check_added_monitors!(nodes[1], 1);
1057         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1058         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
1059
1060         assert!(updates_2.update_add_htlcs.is_empty());
1061         assert!(updates_2.update_fail_htlcs.is_empty());
1062         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
1063         assert!(updates_2.update_fee.is_none());
1064         assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
1065         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
1066         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
1067
1068         let events = nodes[0].node.get_and_clear_pending_events();
1069         assert_eq!(events.len(), 1);
1070         match events[0] {
1071                 Event::PaymentSent { ref payment_preimage } => {
1072                         assert_eq!(our_payment_preimage, *payment_preimage);
1073                 },
1074                 _ => panic!("Unexpected event"),
1075         }
1076
1077         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1078         if recv_count > 0 {
1079                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
1080                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1081                 assert!(node_1_closing_signed.is_some());
1082         }
1083
1084         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1085         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1086
1087         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1088         let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1089         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1090         if recv_count == 0 {
1091                 // If all closing_signeds weren't delivered we can just resume where we left off...
1092                 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1093
1094                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish);
1095                 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1096                 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
1097
1098                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1099                 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1100                 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
1101
1102                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown);
1103                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1104
1105                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown);
1106                 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1107                 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
1108
1109                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed);
1110                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1111                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
1112                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1113                 assert!(node_0_none.is_none());
1114         } else {
1115                 // If one node, however, received + responded with an identical closing_signed we end
1116                 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
1117                 // There isn't really anything better we can do simply, but in the future we might
1118                 // explore storing a set of recently-closed channels that got disconnected during
1119                 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
1120                 // give our counterparty enough time to (potentially) broadcast a cooperative closing
1121                 // transaction.
1122                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1123
1124                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1125                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1126                 assert_eq!(msg_events.len(), 1);
1127                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
1128                         match action {
1129                                 &ErrorAction::SendErrorMessage { ref msg } => {
1130                                         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
1131                                         assert_eq!(msg.channel_id, chan_1.2);
1132                                 },
1133                                 _ => panic!("Unexpected event!"),
1134                         }
1135                 } else { panic!("Needed SendErrorMessage close"); }
1136
1137                 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
1138                 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
1139                 // closing_signed so we do it ourselves
1140                 check_closed_broadcast!(nodes[0], false);
1141                 check_added_monitors!(nodes[0], 1);
1142         }
1143
1144         assert!(nodes[0].node.list_channels().is_empty());
1145
1146         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1147         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1148         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1149         assert!(nodes[1].node.list_channels().is_empty());
1150         assert!(nodes[2].node.list_channels().is_empty());
1151 }
1152
1153 #[test]
1154 fn test_shutdown_rebroadcast() {
1155         do_test_shutdown_rebroadcast(0);
1156         do_test_shutdown_rebroadcast(1);
1157         do_test_shutdown_rebroadcast(2);
1158 }
1159
1160 #[test]
1161 fn fake_network_test() {
1162         // Simple test which builds a network of ChannelManagers, connects them to each other, and
1163         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
1164         let chanmon_cfgs = create_chanmon_cfgs(4);
1165         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1166         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1167         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1168
1169         // Create some initial channels
1170         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1171         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1172         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1173
1174         // Rebalance the network a bit by relaying one payment through all the channels...
1175         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1176         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1177         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1178         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1179
1180         // Send some more payments
1181         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000, 1_000_000);
1182         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000, 1_000_000);
1183         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000, 1_000_000);
1184
1185         // Test failure packets
1186         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1187         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1188
1189         // Add a new channel that skips 3
1190         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1191
1192         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000, 1_000_000);
1193         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000, 1_000_000);
1194         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1195         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1196         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1197         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1198         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1199
1200         // Do some rebalance loop payments, simultaneously
1201         let mut hops = Vec::with_capacity(3);
1202         hops.push(RouteHop {
1203                 pubkey: nodes[2].node.get_our_node_id(),
1204                 node_features: NodeFeatures::empty(),
1205                 short_channel_id: chan_2.0.contents.short_channel_id,
1206                 channel_features: ChannelFeatures::empty(),
1207                 fee_msat: 0,
1208                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1209         });
1210         hops.push(RouteHop {
1211                 pubkey: nodes[3].node.get_our_node_id(),
1212                 node_features: NodeFeatures::empty(),
1213                 short_channel_id: chan_3.0.contents.short_channel_id,
1214                 channel_features: ChannelFeatures::empty(),
1215                 fee_msat: 0,
1216                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1217         });
1218         hops.push(RouteHop {
1219                 pubkey: nodes[1].node.get_our_node_id(),
1220                 node_features: NodeFeatures::empty(),
1221                 short_channel_id: chan_4.0.contents.short_channel_id,
1222                 channel_features: ChannelFeatures::empty(),
1223                 fee_msat: 1000000,
1224                 cltv_expiry_delta: TEST_FINAL_CLTV,
1225         });
1226         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;
1227         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;
1228         let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1229
1230         let mut hops = Vec::with_capacity(3);
1231         hops.push(RouteHop {
1232                 pubkey: nodes[3].node.get_our_node_id(),
1233                 node_features: NodeFeatures::empty(),
1234                 short_channel_id: chan_4.0.contents.short_channel_id,
1235                 channel_features: ChannelFeatures::empty(),
1236                 fee_msat: 0,
1237                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1238         });
1239         hops.push(RouteHop {
1240                 pubkey: nodes[2].node.get_our_node_id(),
1241                 node_features: NodeFeatures::empty(),
1242                 short_channel_id: chan_3.0.contents.short_channel_id,
1243                 channel_features: ChannelFeatures::empty(),
1244                 fee_msat: 0,
1245                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1246         });
1247         hops.push(RouteHop {
1248                 pubkey: nodes[1].node.get_our_node_id(),
1249                 node_features: NodeFeatures::empty(),
1250                 short_channel_id: chan_2.0.contents.short_channel_id,
1251                 channel_features: ChannelFeatures::empty(),
1252                 fee_msat: 1000000,
1253                 cltv_expiry_delta: TEST_FINAL_CLTV,
1254         });
1255         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;
1256         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;
1257         let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1258
1259         // Claim the rebalances...
1260         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1261         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1, 1_000_000);
1262
1263         // Add a duplicate new channel from 2 to 4
1264         let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1265
1266         // Send some payments across both channels
1267         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1268         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1269         let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1270
1271
1272         route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1273         let events = nodes[0].node.get_and_clear_pending_msg_events();
1274         assert_eq!(events.len(), 0);
1275         nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us over the max HTLC value in flight our peer will accept".to_string(), 1);
1276
1277         //TODO: Test that routes work again here as we've been notified that the channel is full
1278
1279         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3, 3_000_000);
1280         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4, 3_000_000);
1281         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5, 3_000_000);
1282
1283         // Close down the channels...
1284         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1285         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1286         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1287         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1288         close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1289 }
1290
1291 #[test]
1292 fn holding_cell_htlc_counting() {
1293         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1294         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1295         // commitment dance rounds.
1296         let chanmon_cfgs = create_chanmon_cfgs(3);
1297         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1298         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1299         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1300         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1301         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1302         let logger = Arc::new(test_utils::TestLogger::new());
1303
1304         let mut payments = Vec::new();
1305         for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1306                 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1307                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1308                 let route = get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, logger.clone()).unwrap();
1309                 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
1310                 payments.push((payment_preimage, payment_hash));
1311         }
1312         check_added_monitors!(nodes[1], 1);
1313
1314         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1315         assert_eq!(events.len(), 1);
1316         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1317         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1318
1319         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1320         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1321         // another HTLC.
1322         let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
1323         {
1324                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1325                 let route = get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, logger.clone()).unwrap();
1326                 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &None), true, APIError::ChannelUnavailable { err },
1327                         assert_eq!(err, "Cannot push more than their max accepted HTLCs"));
1328                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1329                 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1330         }
1331
1332         // This should also be true if we try to forward a payment.
1333         let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
1334         {
1335                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1336                 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, logger.clone()).unwrap();
1337                 nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
1338                 check_added_monitors!(nodes[0], 1);
1339         }
1340
1341         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1342         assert_eq!(events.len(), 1);
1343         let payment_event = SendEvent::from_event(events.pop().unwrap());
1344         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1345
1346         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1347         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1348         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1349         // fails), the second will process the resulting failure and fail the HTLC backward.
1350         expect_pending_htlcs_forwardable!(nodes[1]);
1351         expect_pending_htlcs_forwardable!(nodes[1]);
1352         check_added_monitors!(nodes[1], 1);
1353
1354         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1355         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1356         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1357
1358         let events = nodes[0].node.get_and_clear_pending_msg_events();
1359         assert_eq!(events.len(), 1);
1360         match events[0] {
1361                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
1362                         assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
1363                 },
1364                 _ => panic!("Unexpected event"),
1365         }
1366
1367         expect_payment_failed!(nodes[0], payment_hash_2, false);
1368
1369         // Now forward all the pending HTLCs and claim them back
1370         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1371         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1372         check_added_monitors!(nodes[2], 1);
1373
1374         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1375         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1376         check_added_monitors!(nodes[1], 1);
1377         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1378
1379         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1380         check_added_monitors!(nodes[1], 1);
1381         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1382
1383         for ref update in as_updates.update_add_htlcs.iter() {
1384                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1385         }
1386         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1387         check_added_monitors!(nodes[2], 1);
1388         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1389         check_added_monitors!(nodes[2], 1);
1390         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1391
1392         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1393         check_added_monitors!(nodes[1], 1);
1394         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1395         check_added_monitors!(nodes[1], 1);
1396         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1397
1398         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1399         check_added_monitors!(nodes[2], 1);
1400
1401         expect_pending_htlcs_forwardable!(nodes[2]);
1402
1403         let events = nodes[2].node.get_and_clear_pending_events();
1404         assert_eq!(events.len(), payments.len());
1405         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1406                 match event {
1407                         &Event::PaymentReceived { ref payment_hash, .. } => {
1408                                 assert_eq!(*payment_hash, *hash);
1409                         },
1410                         _ => panic!("Unexpected event"),
1411                 };
1412         }
1413
1414         for (preimage, _) in payments.drain(..) {
1415                 claim_payment(&nodes[1], &[&nodes[2]], preimage, 100_000);
1416         }
1417
1418         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000, 1_000_000);
1419 }
1420
1421 #[test]
1422 fn duplicate_htlc_test() {
1423         // Test that we accept duplicate payment_hash HTLCs across the network and that
1424         // claiming/failing them are all separate and don't affect each other
1425         let chanmon_cfgs = create_chanmon_cfgs(6);
1426         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1427         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1428         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1429
1430         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1431         create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1432         create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1433         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1434         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1435         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1436
1437         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1438
1439         *nodes[0].network_payment_count.borrow_mut() -= 1;
1440         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1441
1442         *nodes[0].network_payment_count.borrow_mut() -= 1;
1443         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1444
1445         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage, 1_000_000);
1446         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1447         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage, 1_000_000);
1448 }
1449
1450 #[test]
1451 fn test_duplicate_htlc_different_direction_onchain() {
1452         // Test that ChannelMonitor doesn't generate 2 preimage txn
1453         // when we have 2 HTLCs with same preimage that go across a node
1454         // in opposite directions.
1455         let chanmon_cfgs = create_chanmon_cfgs(2);
1456         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1457         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1458         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1459
1460         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1461         let logger = Arc::new(test_utils::TestLogger::new());
1462
1463         // balancing
1464         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
1465
1466         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1467
1468         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1469         let route = get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[0].node.get_our_node_id(), None, &Vec::new(), 800_000, TEST_FINAL_CLTV, logger.clone()).unwrap();
1470         send_along_route_with_hash(&nodes[1], route, &vec!(&nodes[0])[..], 800_000, payment_hash);
1471
1472         // Provide preimage to node 0 by claiming payment
1473         nodes[0].node.claim_funds(payment_preimage, &None, 800_000);
1474         check_added_monitors!(nodes[0], 1);
1475
1476         // Broadcast node 1 commitment txn
1477         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1478
1479         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1480         let mut has_both_htlcs = 0; // check htlcs match ones committed
1481         for outp in remote_txn[0].output.iter() {
1482                 if outp.value == 800_000 / 1000 {
1483                         has_both_htlcs += 1;
1484                 } else if outp.value == 900_000 / 1000 {
1485                         has_both_htlcs += 1;
1486                 }
1487         }
1488         assert_eq!(has_both_htlcs, 2);
1489
1490         let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1491         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
1492         check_added_monitors!(nodes[0], 1);
1493
1494         // Check we only broadcast 1 timeout tx
1495         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1496         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()) };
1497         assert_eq!(claim_txn.len(), 5);
1498         check_spends!(claim_txn[2], chan_1.3);
1499         check_spends!(claim_txn[3], claim_txn[2]);
1500         assert_eq!(htlc_pair.0.input.len(), 1);
1501         assert_eq!(htlc_pair.0.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1502         check_spends!(htlc_pair.0, remote_txn[0]);
1503         assert_eq!(htlc_pair.1.input.len(), 1);
1504         assert_eq!(htlc_pair.1.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1505         check_spends!(htlc_pair.1, remote_txn[0]);
1506
1507         let events = nodes[0].node.get_and_clear_pending_msg_events();
1508         assert_eq!(events.len(), 2);
1509         for e in events {
1510                 match e {
1511                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1512                         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, .. } } => {
1513                                 assert!(update_add_htlcs.is_empty());
1514                                 assert!(update_fail_htlcs.is_empty());
1515                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1516                                 assert!(update_fail_malformed_htlcs.is_empty());
1517                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1518                         },
1519                         _ => panic!("Unexpected event"),
1520                 }
1521         }
1522 }
1523
1524 fn do_channel_reserve_test(test_recv: bool) {
1525
1526         let chanmon_cfgs = create_chanmon_cfgs(3);
1527         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1528         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1529         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1530         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1900, 1001, InitFeatures::known(), InitFeatures::known());
1531         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1900, 1001, InitFeatures::known(), InitFeatures::known());
1532         let logger = Arc::new(test_utils::TestLogger::new());
1533
1534         let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1535         let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1536
1537         let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1538         let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1539
1540         macro_rules! get_route_and_payment_hash {
1541                 ($recv_value: expr) => {{
1542                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1543                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1544                         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, logger.clone()).unwrap();
1545                         (route, payment_hash, payment_preimage)
1546                 }}
1547         };
1548
1549         macro_rules! expect_forward {
1550                 ($node: expr) => {{
1551                         let mut events = $node.node.get_and_clear_pending_msg_events();
1552                         assert_eq!(events.len(), 1);
1553                         check_added_monitors!($node, 1);
1554                         let payment_event = SendEvent::from_event(events.remove(0));
1555                         payment_event
1556                 }}
1557         }
1558
1559         let feemsat = 239; // somehow we know?
1560         let total_fee_msat = (nodes.len() - 2) as u64 * 239;
1561
1562         let recv_value_0 = stat01.their_max_htlc_value_in_flight_msat - total_fee_msat;
1563
1564         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1565         {
1566                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
1567                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1568                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
1569                         assert_eq!(err, "Cannot send value that would put us over the max HTLC value in flight our peer will accept"));
1570                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1571                 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us over the max HTLC value in flight our peer will accept".to_string(), 1);
1572         }
1573
1574         let mut htlc_id = 0;
1575         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1576         // nodes[0]'s wealth
1577         loop {
1578                 let amt_msat = recv_value_0 + total_fee_msat;
1579                 if stat01.value_to_self_msat - amt_msat < stat01.channel_reserve_msat {
1580                         break;
1581                 }
1582                 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0, recv_value_0);
1583                 htlc_id += 1;
1584
1585                 let (stat01_, stat11_, stat12_, stat22_) = (
1586                         get_channel_value_stat!(nodes[0], chan_1.2),
1587                         get_channel_value_stat!(nodes[1], chan_1.2),
1588                         get_channel_value_stat!(nodes[1], chan_2.2),
1589                         get_channel_value_stat!(nodes[2], chan_2.2),
1590                 );
1591
1592                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1593                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1594                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1595                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1596                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1597         }
1598
1599         {
1600                 let recv_value = stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat;
1601                 // attempt to get channel_reserve violation
1602                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value + 1);
1603                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
1604                         assert_eq!(err, "Cannot send value that would put us under local channel reserve value"));
1605                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1606                 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us under local channel reserve value".to_string(), 1);
1607         }
1608
1609         // adding pending output
1610         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat)/2;
1611         let amt_msat_1 = recv_value_1 + total_fee_msat;
1612
1613         let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
1614         let payment_event_1 = {
1615                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
1616                 check_added_monitors!(nodes[0], 1);
1617
1618                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1619                 assert_eq!(events.len(), 1);
1620                 SendEvent::from_event(events.remove(0))
1621         };
1622         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1623
1624         // channel reserve test with htlc pending output > 0
1625         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat;
1626         {
1627                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
1628                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
1629                         assert_eq!(err, "Cannot send value that would put us under local channel reserve value"));
1630                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1631                 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us under local channel reserve value".to_string(), 2);
1632         }
1633
1634         {
1635                 // test channel_reserve test on nodes[1] side
1636                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
1637
1638                 // Need to manually create update_add_htlc message to go around the channel reserve check in send_htlc()
1639                 let secp_ctx = Secp256k1::new();
1640                 let session_priv = SecretKey::from_slice(&{
1641                         let mut session_key = [0; 32];
1642                         let mut rng = thread_rng();
1643                         rng.fill_bytes(&mut session_key);
1644                         session_key
1645                 }).expect("RNG is bad!");
1646
1647                 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1648                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1649                 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], recv_value_2 + 1, &None, cur_height).unwrap();
1650                 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
1651                 let msg = msgs::UpdateAddHTLC {
1652                         channel_id: chan_1.2,
1653                         htlc_id,
1654                         amount_msat: htlc_msat,
1655                         payment_hash: our_payment_hash,
1656                         cltv_expiry: htlc_cltv,
1657                         onion_routing_packet: onion_packet,
1658                 };
1659
1660                 if test_recv {
1661                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1662                         // If we send a garbage message, the channel should get closed, making the rest of this test case fail.
1663                         assert_eq!(nodes[1].node.list_channels().len(), 1);
1664                         assert_eq!(nodes[1].node.list_channels().len(), 1);
1665                         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1666                         assert_eq!(err_msg.data, "Remote HTLC add would put them under their reserve value");
1667                         check_added_monitors!(nodes[1], 1);
1668                         return;
1669                 }
1670         }
1671
1672         // split the rest to test holding cell
1673         let recv_value_21 = recv_value_2/2;
1674         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat;
1675         {
1676                 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1677                 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);
1678         }
1679
1680         // now see if they go through on both sides
1681         let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
1682         // but this will stuck in the holding cell
1683         nodes[0].node.send_payment(&route_21, our_payment_hash_21, &None).unwrap();
1684         check_added_monitors!(nodes[0], 0);
1685         let events = nodes[0].node.get_and_clear_pending_events();
1686         assert_eq!(events.len(), 0);
1687
1688         // test with outbound holding cell amount > 0
1689         {
1690                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
1691                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
1692                         assert_eq!(err, "Cannot send value that would put us under local channel reserve value"));
1693                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1694                 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us under local channel reserve value".to_string(), 3);
1695         }
1696
1697         let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
1698         // this will also stuck in the holding cell
1699         nodes[0].node.send_payment(&route_22, our_payment_hash_22, &None).unwrap();
1700         check_added_monitors!(nodes[0], 0);
1701         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1702         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1703
1704         // flush the pending htlc
1705         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1706         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1707         check_added_monitors!(nodes[1], 1);
1708
1709         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1710         check_added_monitors!(nodes[0], 1);
1711         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1712
1713         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1714         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1715         // No commitment_signed so get_event_msg's assert(len == 1) passes
1716         check_added_monitors!(nodes[0], 1);
1717
1718         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1719         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1720         check_added_monitors!(nodes[1], 1);
1721
1722         expect_pending_htlcs_forwardable!(nodes[1]);
1723
1724         let ref payment_event_11 = expect_forward!(nodes[1]);
1725         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1726         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1727
1728         expect_pending_htlcs_forwardable!(nodes[2]);
1729         expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
1730
1731         // flush the htlcs in the holding cell
1732         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1733         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1734         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1735         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1736         expect_pending_htlcs_forwardable!(nodes[1]);
1737
1738         let ref payment_event_3 = expect_forward!(nodes[1]);
1739         assert_eq!(payment_event_3.msgs.len(), 2);
1740         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1741         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1742
1743         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1744         expect_pending_htlcs_forwardable!(nodes[2]);
1745
1746         let events = nodes[2].node.get_and_clear_pending_events();
1747         assert_eq!(events.len(), 2);
1748         match events[0] {
1749                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
1750                         assert_eq!(our_payment_hash_21, *payment_hash);
1751                         assert_eq!(*payment_secret, None);
1752                         assert_eq!(recv_value_21, amt);
1753                 },
1754                 _ => panic!("Unexpected event"),
1755         }
1756         match events[1] {
1757                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
1758                         assert_eq!(our_payment_hash_22, *payment_hash);
1759                         assert_eq!(None, *payment_secret);
1760                         assert_eq!(recv_value_22, amt);
1761                 },
1762                 _ => panic!("Unexpected event"),
1763         }
1764
1765         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1, recv_value_1);
1766         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21, recv_value_21);
1767         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22, recv_value_22);
1768
1769         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);
1770         let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
1771         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
1772         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat);
1773
1774         let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
1775         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22);
1776 }
1777
1778 #[test]
1779 fn channel_reserve_test() {
1780         do_channel_reserve_test(false);
1781         do_channel_reserve_test(true);
1782 }
1783
1784 #[test]
1785 fn channel_reserve_in_flight_removes() {
1786         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
1787         // can send to its counterparty, but due to update ordering, the other side may not yet have
1788         // considered those HTLCs fully removed.
1789         // This tests that we don't count HTLCs which will not be included in the next remote
1790         // commitment transaction towards the reserve value (as it implies no commitment transaction
1791         // will be generated which violates the remote reserve value).
1792         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
1793         // To test this we:
1794         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
1795         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
1796         //    you only consider the value of the first HTLC, it may not),
1797         //  * start routing a third HTLC from A to B,
1798         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
1799         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
1800         //  * deliver the first fulfill from B
1801         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
1802         //    claim,
1803         //  * deliver A's response CS and RAA.
1804         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
1805         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
1806         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
1807         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
1808         let chanmon_cfgs = create_chanmon_cfgs(2);
1809         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1810         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1811         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1812         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1813         let logger = Arc::new(test_utils::TestLogger::new());
1814
1815         let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
1816         // Route the first two HTLCs.
1817         let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
1818         let (payment_preimage_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
1819
1820         // Start routing the third HTLC (this is just used to get everyone in the right state).
1821         let (payment_preimage_3, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
1822         let send_1 = {
1823                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1824                 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, logger.clone()).unwrap();
1825                 nodes[0].node.send_payment(&route, payment_hash_3, &None).unwrap();
1826                 check_added_monitors!(nodes[0], 1);
1827                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1828                 assert_eq!(events.len(), 1);
1829                 SendEvent::from_event(events.remove(0))
1830         };
1831
1832         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
1833         // initial fulfill/CS.
1834         assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000));
1835         check_added_monitors!(nodes[1], 1);
1836         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1837
1838         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
1839         // remove the second HTLC when we send the HTLC back from B to A.
1840         assert!(nodes[1].node.claim_funds(payment_preimage_2, &None, 20000));
1841         check_added_monitors!(nodes[1], 1);
1842         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1843
1844         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
1845         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
1846         check_added_monitors!(nodes[0], 1);
1847         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1848         expect_payment_sent!(nodes[0], payment_preimage_1);
1849
1850         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
1851         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
1852         check_added_monitors!(nodes[1], 1);
1853         // B is already AwaitingRAA, so cant generate a CS here
1854         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1855
1856         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1857         check_added_monitors!(nodes[1], 1);
1858         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1859
1860         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1861         check_added_monitors!(nodes[0], 1);
1862         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1863
1864         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1865         check_added_monitors!(nodes[1], 1);
1866         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1867
1868         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
1869         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
1870         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
1871         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
1872         // on-chain as necessary).
1873         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
1874         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
1875         check_added_monitors!(nodes[0], 1);
1876         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1877         expect_payment_sent!(nodes[0], payment_preimage_2);
1878
1879         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1880         check_added_monitors!(nodes[1], 1);
1881         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1882
1883         expect_pending_htlcs_forwardable!(nodes[1]);
1884         expect_payment_received!(nodes[1], payment_hash_3, 100000);
1885
1886         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
1887         // resolve the second HTLC from A's point of view.
1888         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1889         check_added_monitors!(nodes[0], 1);
1890         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1891
1892         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
1893         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
1894         let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[1]);
1895         let send_2 = {
1896                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1897                 let route = get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[0].node.get_our_node_id(), None, &[], 10000, TEST_FINAL_CLTV, logger.clone()).unwrap();
1898                 nodes[1].node.send_payment(&route, payment_hash_4, &None).unwrap();
1899                 check_added_monitors!(nodes[1], 1);
1900                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1901                 assert_eq!(events.len(), 1);
1902                 SendEvent::from_event(events.remove(0))
1903         };
1904
1905         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
1906         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
1907         check_added_monitors!(nodes[0], 1);
1908         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1909
1910         // Now just resolve all the outstanding messages/HTLCs for completeness...
1911
1912         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1913         check_added_monitors!(nodes[1], 1);
1914         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1915
1916         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1917         check_added_monitors!(nodes[1], 1);
1918
1919         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1920         check_added_monitors!(nodes[0], 1);
1921         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1922
1923         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1924         check_added_monitors!(nodes[1], 1);
1925         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1926
1927         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1928         check_added_monitors!(nodes[0], 1);
1929
1930         expect_pending_htlcs_forwardable!(nodes[0]);
1931         expect_payment_received!(nodes[0], payment_hash_4, 10000);
1932
1933         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4, 10_000);
1934         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3, 100_000);
1935 }
1936
1937 #[test]
1938 fn channel_monitor_network_test() {
1939         // Simple test which builds a network of ChannelManagers, connects them to each other, and
1940         // tests that ChannelMonitor is able to recover from various states.
1941         let chanmon_cfgs = create_chanmon_cfgs(5);
1942         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
1943         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
1944         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
1945
1946         // Create some initial channels
1947         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1948         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1949         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1950         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1951
1952         // Rebalance the network a bit by relaying one payment through all the channels...
1953         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
1954         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
1955         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
1956         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
1957
1958         // Simple case with no pending HTLCs:
1959         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
1960         check_added_monitors!(nodes[1], 1);
1961         {
1962                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
1963                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1964                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
1965                 check_added_monitors!(nodes[0], 1);
1966                 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
1967         }
1968         get_announce_close_broadcast_events(&nodes, 0, 1);
1969         assert_eq!(nodes[0].node.list_channels().len(), 0);
1970         assert_eq!(nodes[1].node.list_channels().len(), 1);
1971
1972         // One pending HTLC is discarded by the force-close:
1973         let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
1974
1975         // Simple case of one pending HTLC to HTLC-Timeout
1976         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
1977         check_added_monitors!(nodes[1], 1);
1978         {
1979                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
1980                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1981                 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
1982                 check_added_monitors!(nodes[2], 1);
1983                 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
1984         }
1985         get_announce_close_broadcast_events(&nodes, 1, 2);
1986         assert_eq!(nodes[1].node.list_channels().len(), 0);
1987         assert_eq!(nodes[2].node.list_channels().len(), 1);
1988
1989         macro_rules! claim_funds {
1990                 ($node: expr, $prev_node: expr, $preimage: expr, $amount: expr) => {
1991                         {
1992                                 assert!($node.node.claim_funds($preimage, &None, $amount));
1993                                 check_added_monitors!($node, 1);
1994
1995                                 let events = $node.node.get_and_clear_pending_msg_events();
1996                                 assert_eq!(events.len(), 1);
1997                                 match events[0] {
1998                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
1999                                                 assert!(update_add_htlcs.is_empty());
2000                                                 assert!(update_fail_htlcs.is_empty());
2001                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2002                                         },
2003                                         _ => panic!("Unexpected event"),
2004                                 };
2005                         }
2006                 }
2007         }
2008
2009         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2010         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2011         nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2012         check_added_monitors!(nodes[2], 1);
2013         let node2_commitment_txid;
2014         {
2015                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2016                 node2_commitment_txid = node_txn[0].txid();
2017
2018                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2019                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, 3_000_000);
2020
2021                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2022                 nodes[3].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
2023                 check_added_monitors!(nodes[3], 1);
2024
2025                 check_preimage_claim(&nodes[3], &node_txn);
2026         }
2027         get_announce_close_broadcast_events(&nodes, 2, 3);
2028         assert_eq!(nodes[2].node.list_channels().len(), 0);
2029         assert_eq!(nodes[3].node.list_channels().len(), 1);
2030
2031         { // Cheat and reset nodes[4]'s height to 1
2032                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2033                 nodes[4].block_notifier.block_connected(&Block { header, txdata: vec![] }, 1);
2034         }
2035
2036         assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
2037         assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
2038         // One pending HTLC to time out:
2039         let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2040         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2041         // buffer space).
2042
2043         {
2044                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2045                 nodes[3].block_notifier.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
2046                 for i in 3..TEST_FINAL_CLTV + 2 + LATENCY_GRACE_PERIOD_BLOCKS + 1 {
2047                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2048                         nodes[3].block_notifier.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
2049                 }
2050                 check_added_monitors!(nodes[3], 1);
2051
2052                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2053                 {
2054                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2055                         node_txn.retain(|tx| {
2056                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2057                                         false
2058                                 } else { true }
2059                         });
2060                 }
2061
2062                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2063
2064                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2065                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, 3_000_000);
2066
2067                 header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2068
2069                 nodes[4].block_notifier.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
2070                 for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
2071                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2072                         nodes[4].block_notifier.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
2073                 }
2074
2075                 check_added_monitors!(nodes[4], 1);
2076                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2077
2078                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2079                 nodes[4].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, TEST_FINAL_CLTV - 5);
2080
2081                 check_preimage_claim(&nodes[4], &node_txn);
2082         }
2083         get_announce_close_broadcast_events(&nodes, 3, 4);
2084         assert_eq!(nodes[3].node.list_channels().len(), 0);
2085         assert_eq!(nodes[4].node.list_channels().len(), 0);
2086 }
2087
2088 #[test]
2089 fn test_justice_tx() {
2090         // Test justice txn built on revoked HTLC-Success tx, against both sides
2091         let mut alice_config = UserConfig::default();
2092         alice_config.channel_options.announced_channel = true;
2093         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2094         alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2095         let mut bob_config = UserConfig::default();
2096         bob_config.channel_options.announced_channel = true;
2097         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2098         bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2099         let user_cfgs = [Some(alice_config), Some(bob_config)];
2100         let chanmon_cfgs = create_chanmon_cfgs(2);
2101         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2102         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2103         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2104         // Create some new channels:
2105         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2106
2107         // A pending HTLC which will be revoked:
2108         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2109         // Get the will-be-revoked local txn from nodes[0]
2110         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2111         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2112         assert_eq!(revoked_local_txn[0].input.len(), 1);
2113         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2114         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2115         assert_eq!(revoked_local_txn[1].input.len(), 1);
2116         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2117         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2118         // Revoke the old state
2119         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 3_000_000);
2120
2121         {
2122                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2123                 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2124                 {
2125                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2126                         assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2127                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2128
2129                         check_spends!(node_txn[0], revoked_local_txn[0]);
2130                         node_txn.swap_remove(0);
2131                         node_txn.truncate(1);
2132                 }
2133                 check_added_monitors!(nodes[1], 1);
2134                 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2135
2136                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2137                 // Verify broadcast of revoked HTLC-timeout
2138                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2139                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2140                 check_added_monitors!(nodes[0], 1);
2141                 // Broadcast revoked HTLC-timeout on node 1
2142                 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2143                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2144         }
2145         get_announce_close_broadcast_events(&nodes, 0, 1);
2146
2147         assert_eq!(nodes[0].node.list_channels().len(), 0);
2148         assert_eq!(nodes[1].node.list_channels().len(), 0);
2149
2150         // We test justice_tx build by A on B's revoked HTLC-Success tx
2151         // Create some new channels:
2152         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2153         {
2154                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2155                 node_txn.clear();
2156         }
2157
2158         // A pending HTLC which will be revoked:
2159         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2160         // Get the will-be-revoked local txn from B
2161         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2162         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2163         assert_eq!(revoked_local_txn[0].input.len(), 1);
2164         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2165         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2166         // Revoke the old state
2167         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4, 3_000_000);
2168         {
2169                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2170                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2171                 {
2172                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2173                         assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2174                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2175
2176                         check_spends!(node_txn[0], revoked_local_txn[0]);
2177                         node_txn.swap_remove(0);
2178                 }
2179                 check_added_monitors!(nodes[0], 1);
2180                 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2181
2182                 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2183                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2184                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2185                 check_added_monitors!(nodes[1], 1);
2186                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2187                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2188         }
2189         get_announce_close_broadcast_events(&nodes, 0, 1);
2190         assert_eq!(nodes[0].node.list_channels().len(), 0);
2191         assert_eq!(nodes[1].node.list_channels().len(), 0);
2192 }
2193
2194 #[test]
2195 fn revoked_output_claim() {
2196         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2197         // transaction is broadcast by its counterparty
2198         let chanmon_cfgs = create_chanmon_cfgs(2);
2199         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2200         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2201         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2202         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2203         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2204         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2205         assert_eq!(revoked_local_txn.len(), 1);
2206         // Only output is the full channel value back to nodes[0]:
2207         assert_eq!(revoked_local_txn[0].output.len(), 1);
2208         // Send a payment through, updating everyone's latest commitment txn
2209         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000, 5_000_000);
2210
2211         // Inform nodes[1] that nodes[0] broadcast a stale tx
2212         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2213         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2214         check_added_monitors!(nodes[1], 1);
2215         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2216         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2217
2218         check_spends!(node_txn[0], revoked_local_txn[0]);
2219         check_spends!(node_txn[1], chan_1.3);
2220
2221         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2222         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2223         get_announce_close_broadcast_events(&nodes, 0, 1);
2224         check_added_monitors!(nodes[0], 1)
2225 }
2226
2227 #[test]
2228 fn claim_htlc_outputs_shared_tx() {
2229         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2230         let chanmon_cfgs = create_chanmon_cfgs(2);
2231         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2232         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2233         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2234
2235         // Create some new channel:
2236         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2237
2238         // Rebalance the network to generate htlc in the two directions
2239         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2240         // 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
2241         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2242         let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2243
2244         // Get the will-be-revoked local txn from node[0]
2245         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2246         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2247         assert_eq!(revoked_local_txn[0].input.len(), 1);
2248         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2249         assert_eq!(revoked_local_txn[1].input.len(), 1);
2250         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2251         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2252         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2253
2254         //Revoke the old state
2255         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2256
2257         {
2258                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2259                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2260                 check_added_monitors!(nodes[0], 1);
2261                 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2262                 check_added_monitors!(nodes[1], 1);
2263                 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2264                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2265
2266                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2267                 assert_eq!(node_txn.len(), 3); // ChannelMonitor: penalty tx, ChannelManager: local commitment + HTLC-timeout
2268
2269                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2270                 check_spends!(node_txn[0], revoked_local_txn[0]);
2271
2272                 let mut witness_lens = BTreeSet::new();
2273                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2274                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2275                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2276                 assert_eq!(witness_lens.len(), 3);
2277                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2278                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2279                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2280
2281                 // Next nodes[1] broadcasts its current local tx state:
2282                 assert_eq!(node_txn[1].input.len(), 1);
2283                 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2284
2285                 assert_eq!(node_txn[2].input.len(), 1);
2286                 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
2287                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2288                 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
2289                 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
2290                 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
2291         }
2292         get_announce_close_broadcast_events(&nodes, 0, 1);
2293         assert_eq!(nodes[0].node.list_channels().len(), 0);
2294         assert_eq!(nodes[1].node.list_channels().len(), 0);
2295 }
2296
2297 #[test]
2298 fn claim_htlc_outputs_single_tx() {
2299         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2300         let chanmon_cfgs = create_chanmon_cfgs(2);
2301         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2302         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2303         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2304
2305         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2306
2307         // Rebalance the network to generate htlc in the two directions
2308         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2309         // 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
2310         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2311         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2312         let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2313
2314         // Get the will-be-revoked local txn from node[0]
2315         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2316
2317         //Revoke the old state
2318         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2319
2320         {
2321                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2322                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2323                 check_added_monitors!(nodes[0], 1);
2324                 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2325                 check_added_monitors!(nodes[1], 1);
2326                 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
2327
2328                 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 200, true, header.bitcoin_hash());
2329                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2330
2331                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2332                 assert_eq!(node_txn.len(), 9);
2333                 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2334                 // ChannelManager: local commmitment + local HTLC-timeout (2)
2335                 // ChannelMonitor: bumped justice tx, after one increase, bumps on HTLC aren't generated not being substantial anymore, bump on revoked to_local isn't generated due to more room for expiration (2)
2336                 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2337
2338                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2339                 assert_eq!(node_txn[2].input.len(), 1);
2340                 check_spends!(node_txn[2], chan_1.3);
2341                 assert_eq!(node_txn[3].input.len(), 1);
2342                 let witness_script = node_txn[3].input[0].witness.last().unwrap();
2343                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2344                 check_spends!(node_txn[3], node_txn[2]);
2345
2346                 // Justice transactions are indices 1-2-4
2347                 assert_eq!(node_txn[0].input.len(), 1);
2348                 assert_eq!(node_txn[1].input.len(), 1);
2349                 assert_eq!(node_txn[4].input.len(), 1);
2350
2351                 check_spends!(node_txn[0], revoked_local_txn[0]);
2352                 check_spends!(node_txn[1], revoked_local_txn[0]);
2353                 check_spends!(node_txn[4], revoked_local_txn[0]);
2354
2355                 let mut witness_lens = BTreeSet::new();
2356                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2357                 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2358                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2359                 assert_eq!(witness_lens.len(), 3);
2360                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2361                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2362                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2363         }
2364         get_announce_close_broadcast_events(&nodes, 0, 1);
2365         assert_eq!(nodes[0].node.list_channels().len(), 0);
2366         assert_eq!(nodes[1].node.list_channels().len(), 0);
2367 }
2368
2369 #[test]
2370 fn test_htlc_on_chain_success() {
2371         // Test that in case of a unilateral close onchain, we detect the state of output thanks to
2372         // ChainWatchInterface and pass the preimage backward accordingly. So here we test that ChannelManager is
2373         // broadcasting the right event to other nodes in payment path.
2374         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2375         // A --------------------> B ----------------------> C (preimage)
2376         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2377         // commitment transaction was broadcast.
2378         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2379         // towards B.
2380         // B should be able to claim via preimage if A then broadcasts its local tx.
2381         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2382         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2383         // PaymentSent event).
2384
2385         let chanmon_cfgs = create_chanmon_cfgs(3);
2386         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2387         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2388         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2389
2390         // Create some initial channels
2391         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2392         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2393
2394         // Rebalance the network a bit by relaying one payment through all the channels...
2395         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2396         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2397
2398         let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2399         let (our_payment_preimage_2, _payment_hash_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2400         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2401
2402         // Broadcast legit commitment tx from C on B's chain
2403         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2404         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2405         assert_eq!(commitment_tx.len(), 1);
2406         check_spends!(commitment_tx[0], chan_2.3);
2407         nodes[2].node.claim_funds(our_payment_preimage, &None, 3_000_000);
2408         nodes[2].node.claim_funds(our_payment_preimage_2, &None, 3_000_000);
2409         check_added_monitors!(nodes[2], 2);
2410         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2411         assert!(updates.update_add_htlcs.is_empty());
2412         assert!(updates.update_fail_htlcs.is_empty());
2413         assert!(updates.update_fail_malformed_htlcs.is_empty());
2414         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2415
2416         nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2417         check_closed_broadcast!(nodes[2], false);
2418         check_added_monitors!(nodes[2], 1);
2419         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx, 2*htlc-success tx), ChannelMonitor : 2 (2 * HTLC-Success tx)
2420         assert_eq!(node_txn.len(), 5);
2421         assert_eq!(node_txn[0], node_txn[3]);
2422         assert_eq!(node_txn[1], node_txn[4]);
2423         assert_eq!(node_txn[2], commitment_tx[0]);
2424         check_spends!(node_txn[0], commitment_tx[0]);
2425         check_spends!(node_txn[1], commitment_tx[0]);
2426         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2427         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2428         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2429         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2430         assert_eq!(node_txn[0].lock_time, 0);
2431         assert_eq!(node_txn[1].lock_time, 0);
2432
2433         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2434         nodes[1].block_notifier.block_connected(&Block { header, txdata: node_txn}, 1);
2435         {
2436                 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
2437                 assert_eq!(added_monitors.len(), 1);
2438                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2439                 added_monitors.clear();
2440         }
2441         let events = nodes[1].node.get_and_clear_pending_msg_events();
2442         {
2443                 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
2444                 assert_eq!(added_monitors.len(), 2);
2445                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2446                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2447                 added_monitors.clear();
2448         }
2449         assert_eq!(events.len(), 2);
2450         match events[0] {
2451                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2452                 _ => panic!("Unexpected event"),
2453         }
2454         match events[1] {
2455                 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, .. } } => {
2456                         assert!(update_add_htlcs.is_empty());
2457                         assert!(update_fail_htlcs.is_empty());
2458                         assert_eq!(update_fulfill_htlcs.len(), 1);
2459                         assert!(update_fail_malformed_htlcs.is_empty());
2460                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2461                 },
2462                 _ => panic!("Unexpected event"),
2463         };
2464         macro_rules! check_tx_local_broadcast {
2465                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2466                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2467                         assert_eq!(node_txn.len(), 5);
2468                         // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2469                         // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2470                         check_spends!(node_txn[0], $commitment_tx);
2471                         check_spends!(node_txn[1], $commitment_tx);
2472                         assert_ne!(node_txn[0].lock_time, 0);
2473                         assert_ne!(node_txn[1].lock_time, 0);
2474                         if $htlc_offered {
2475                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2476                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2477                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2478                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2479                         } else {
2480                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2481                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2482                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2483                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2484                         }
2485                         check_spends!(node_txn[2], $chan_tx);
2486                         check_spends!(node_txn[3], node_txn[2]);
2487                         check_spends!(node_txn[4], node_txn[2]);
2488                         assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), 71);
2489                         assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2490                         assert_eq!(node_txn[4].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2491                         assert!(node_txn[3].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2492                         assert!(node_txn[4].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2493                         assert_ne!(node_txn[3].lock_time, 0);
2494                         assert_ne!(node_txn[4].lock_time, 0);
2495                         node_txn.clear();
2496                 } }
2497         }
2498         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2499         // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2500         // timeout-claim of the output that nodes[2] just claimed via success.
2501         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2502
2503         // Broadcast legit commitment tx from A on B's chain
2504         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2505         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2506         check_spends!(commitment_tx[0], chan_1.3);
2507         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2508         check_closed_broadcast!(nodes[1], false);
2509         check_added_monitors!(nodes[1], 1);
2510         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 1 (HTLC-Success)
2511         assert_eq!(node_txn.len(), 4);
2512         check_spends!(node_txn[0], commitment_tx[0]);
2513         assert_eq!(node_txn[0].input.len(), 2);
2514         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2515         assert_eq!(node_txn[0].input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2516         assert_eq!(node_txn[0].lock_time, 0);
2517         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2518         check_spends!(node_txn[1], chan_1.3);
2519         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
2520         check_spends!(node_txn[2], node_txn[1]);
2521         check_spends!(node_txn[3], node_txn[1]);
2522         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2523         // we already checked the same situation with A.
2524
2525         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2526         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
2527         check_closed_broadcast!(nodes[0], false);
2528         check_added_monitors!(nodes[0], 1);
2529         let events = nodes[0].node.get_and_clear_pending_events();
2530         assert_eq!(events.len(), 2);
2531         let mut first_claimed = false;
2532         for event in events {
2533                 match event {
2534                         Event::PaymentSent { payment_preimage } => {
2535                                 if payment_preimage == our_payment_preimage {
2536                                         assert!(!first_claimed);
2537                                         first_claimed = true;
2538                                 } else {
2539                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2540                                 }
2541                         },
2542                         _ => panic!("Unexpected event"),
2543                 }
2544         }
2545         check_tx_local_broadcast!(nodes[0], true, commitment_tx[0], chan_1.3);
2546 }
2547
2548 #[test]
2549 fn test_htlc_on_chain_timeout() {
2550         // Test that in case of a unilateral close onchain, we detect the state of output thanks to
2551         // ChainWatchInterface and timeout the HTLC backward accordingly. So here we test that ChannelManager is
2552         // broadcasting the right event to other nodes in payment path.
2553         // A ------------------> B ----------------------> C (timeout)
2554         //    B's commitment tx                 C's commitment tx
2555         //            \                                  \
2556         //         B's HTLC timeout tx               B's timeout tx
2557
2558         let chanmon_cfgs = create_chanmon_cfgs(3);
2559         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2560         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2561         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2562
2563         // Create some intial channels
2564         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2565         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2566
2567         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2568         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2569         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2570
2571         let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2572         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2573
2574         // Broadcast legit commitment tx from C on B's chain
2575         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2576         check_spends!(commitment_tx[0], chan_2.3);
2577         nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
2578         check_added_monitors!(nodes[2], 0);
2579         expect_pending_htlcs_forwardable!(nodes[2]);
2580         check_added_monitors!(nodes[2], 1);
2581
2582         let events = nodes[2].node.get_and_clear_pending_msg_events();
2583         assert_eq!(events.len(), 1);
2584         match events[0] {
2585                 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, .. } } => {
2586                         assert!(update_add_htlcs.is_empty());
2587                         assert!(!update_fail_htlcs.is_empty());
2588                         assert!(update_fulfill_htlcs.is_empty());
2589                         assert!(update_fail_malformed_htlcs.is_empty());
2590                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2591                 },
2592                 _ => panic!("Unexpected event"),
2593         };
2594         nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2595         check_closed_broadcast!(nodes[2], false);
2596         check_added_monitors!(nodes[2], 1);
2597         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2598         assert_eq!(node_txn.len(), 1);
2599         check_spends!(node_txn[0], chan_2.3);
2600         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2601
2602         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2603         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2604         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
2605         let timeout_tx;
2606         {
2607                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2608                 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2609                 assert_eq!(node_txn[1], node_txn[3]);
2610                 assert_eq!(node_txn[2], node_txn[4]);
2611
2612                 check_spends!(node_txn[0], commitment_tx[0]);
2613                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2614
2615                 check_spends!(node_txn[1], chan_2.3);
2616                 check_spends!(node_txn[2], node_txn[1]);
2617                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
2618                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2619
2620                 timeout_tx = node_txn[0].clone();
2621                 node_txn.clear();
2622         }
2623
2624         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![timeout_tx]}, 1);
2625         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2626         check_added_monitors!(nodes[1], 1);
2627         check_closed_broadcast!(nodes[1], false);
2628
2629         expect_pending_htlcs_forwardable!(nodes[1]);
2630         check_added_monitors!(nodes[1], 1);
2631         let events = nodes[1].node.get_and_clear_pending_msg_events();
2632         assert_eq!(events.len(), 1);
2633         match events[0] {
2634                 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, .. } } => {
2635                         assert!(update_add_htlcs.is_empty());
2636                         assert!(!update_fail_htlcs.is_empty());
2637                         assert!(update_fulfill_htlcs.is_empty());
2638                         assert!(update_fail_malformed_htlcs.is_empty());
2639                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2640                 },
2641                 _ => panic!("Unexpected event"),
2642         };
2643         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
2644         assert_eq!(node_txn.len(), 0);
2645
2646         // Broadcast legit commitment tx from B on A's chain
2647         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2648         check_spends!(commitment_tx[0], chan_1.3);
2649
2650         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
2651         check_closed_broadcast!(nodes[0], false);
2652         check_added_monitors!(nodes[0], 1);
2653         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 1 timeout tx
2654         assert_eq!(node_txn.len(), 3);
2655         check_spends!(node_txn[0], commitment_tx[0]);
2656         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2657         check_spends!(node_txn[1], chan_1.3);
2658         check_spends!(node_txn[2], node_txn[1]);
2659         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
2660         assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2661 }
2662
2663 #[test]
2664 fn test_simple_commitment_revoked_fail_backward() {
2665         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
2666         // and fail backward accordingly.
2667
2668         let chanmon_cfgs = create_chanmon_cfgs(3);
2669         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2670         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2671         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2672
2673         // Create some initial channels
2674         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2675         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2676
2677         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2678         // Get the will-be-revoked local txn from nodes[2]
2679         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2680         // Revoke the old state
2681         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, 3_000_000);
2682
2683         let (_, payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2684
2685         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2686         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2687         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2688         check_added_monitors!(nodes[1], 1);
2689         check_closed_broadcast!(nodes[1], false);
2690
2691         expect_pending_htlcs_forwardable!(nodes[1]);
2692         check_added_monitors!(nodes[1], 1);
2693         let events = nodes[1].node.get_and_clear_pending_msg_events();
2694         assert_eq!(events.len(), 1);
2695         match events[0] {
2696                 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, .. } } => {
2697                         assert!(update_add_htlcs.is_empty());
2698                         assert_eq!(update_fail_htlcs.len(), 1);
2699                         assert!(update_fulfill_htlcs.is_empty());
2700                         assert!(update_fail_malformed_htlcs.is_empty());
2701                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2702
2703                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
2704                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2705
2706                         let events = nodes[0].node.get_and_clear_pending_msg_events();
2707                         assert_eq!(events.len(), 1);
2708                         match events[0] {
2709                                 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
2710                                 _ => panic!("Unexpected event"),
2711                         }
2712                         expect_payment_failed!(nodes[0], payment_hash, false);
2713                 },
2714                 _ => panic!("Unexpected event"),
2715         }
2716 }
2717
2718 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
2719         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
2720         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
2721         // commitment transaction anymore.
2722         // To do this, we have the peer which will broadcast a revoked commitment transaction send
2723         // a number of update_fail/commitment_signed updates without ever sending the RAA in
2724         // response to our commitment_signed. This is somewhat misbehavior-y, though not
2725         // technically disallowed and we should probably handle it reasonably.
2726         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
2727         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
2728         // transactions:
2729         // * Once we move it out of our holding cell/add it, we will immediately include it in a
2730         //   commitment_signed (implying it will be in the latest remote commitment transaction).
2731         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
2732         //   and once they revoke the previous commitment transaction (allowing us to send a new
2733         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
2734         let chanmon_cfgs = create_chanmon_cfgs(3);
2735         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2736         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2737         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2738
2739         // Create some initial channels
2740         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2741         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2742
2743         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
2744         // Get the will-be-revoked local txn from nodes[2]
2745         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2746         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
2747         // Revoke the old state
2748         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, if no_to_remote { 10_000 } else { 3_000_000});
2749
2750         let value = if use_dust {
2751                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
2752                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
2753                 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().our_dust_limit_satoshis * 1000
2754         } else { 3000000 };
2755
2756         let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2757         let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2758         let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2759
2760         assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, &None));
2761         expect_pending_htlcs_forwardable!(nodes[2]);
2762         check_added_monitors!(nodes[2], 1);
2763         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2764         assert!(updates.update_add_htlcs.is_empty());
2765         assert!(updates.update_fulfill_htlcs.is_empty());
2766         assert!(updates.update_fail_malformed_htlcs.is_empty());
2767         assert_eq!(updates.update_fail_htlcs.len(), 1);
2768         assert!(updates.update_fee.is_none());
2769         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2770         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
2771         // Drop the last RAA from 3 -> 2
2772
2773         assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, &None));
2774         expect_pending_htlcs_forwardable!(nodes[2]);
2775         check_added_monitors!(nodes[2], 1);
2776         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2777         assert!(updates.update_add_htlcs.is_empty());
2778         assert!(updates.update_fulfill_htlcs.is_empty());
2779         assert!(updates.update_fail_malformed_htlcs.is_empty());
2780         assert_eq!(updates.update_fail_htlcs.len(), 1);
2781         assert!(updates.update_fee.is_none());
2782         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2783         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
2784         check_added_monitors!(nodes[1], 1);
2785         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
2786         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2787         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
2788         check_added_monitors!(nodes[2], 1);
2789
2790         assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, &None));
2791         expect_pending_htlcs_forwardable!(nodes[2]);
2792         check_added_monitors!(nodes[2], 1);
2793         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2794         assert!(updates.update_add_htlcs.is_empty());
2795         assert!(updates.update_fulfill_htlcs.is_empty());
2796         assert!(updates.update_fail_malformed_htlcs.is_empty());
2797         assert_eq!(updates.update_fail_htlcs.len(), 1);
2798         assert!(updates.update_fee.is_none());
2799         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2800         // At this point first_payment_hash has dropped out of the latest two commitment
2801         // transactions that nodes[1] is tracking...
2802         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
2803         check_added_monitors!(nodes[1], 1);
2804         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
2805         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2806         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
2807         check_added_monitors!(nodes[2], 1);
2808
2809         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
2810         // on nodes[2]'s RAA.
2811         let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
2812         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
2813         let logger = Arc::new(test_utils::TestLogger::new());
2814         let route = get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, logger.clone()).unwrap();
2815         nodes[1].node.send_payment(&route, fourth_payment_hash, &None).unwrap();
2816         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2817         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2818         check_added_monitors!(nodes[1], 0);
2819
2820         if deliver_bs_raa {
2821                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
2822                 // One monitor for the new revocation preimage, no second on as we won't generate a new
2823                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
2824                 check_added_monitors!(nodes[1], 1);
2825                 let events = nodes[1].node.get_and_clear_pending_events();
2826                 assert_eq!(events.len(), 1);
2827                 match events[0] {
2828                         Event::PendingHTLCsForwardable { .. } => { },
2829                         _ => panic!("Unexpected event"),
2830                 };
2831                 // Deliberately don't process the pending fail-back so they all fail back at once after
2832                 // block connection just like the !deliver_bs_raa case
2833         }
2834
2835         let mut failed_htlcs = HashSet::new();
2836         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2837
2838         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2839         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2840         check_added_monitors!(nodes[1], 1);
2841         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2842
2843         let events = nodes[1].node.get_and_clear_pending_events();
2844         assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
2845         match events[0] {
2846                 Event::PaymentFailed { ref payment_hash, .. } => {
2847                         assert_eq!(*payment_hash, fourth_payment_hash);
2848                 },
2849                 _ => panic!("Unexpected event"),
2850         }
2851         if !deliver_bs_raa {
2852                 match events[1] {
2853                         Event::PendingHTLCsForwardable { .. } => { },
2854                         _ => panic!("Unexpected event"),
2855                 };
2856         }
2857         nodes[1].node.process_pending_htlc_forwards();
2858         check_added_monitors!(nodes[1], 1);
2859
2860         let events = nodes[1].node.get_and_clear_pending_msg_events();
2861         assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
2862         match events[if deliver_bs_raa { 1 } else { 0 }] {
2863                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
2864                 _ => panic!("Unexpected event"),
2865         }
2866         if deliver_bs_raa {
2867                 match events[0] {
2868                         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, .. } } => {
2869                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
2870                                 assert_eq!(update_add_htlcs.len(), 1);
2871                                 assert!(update_fulfill_htlcs.is_empty());
2872                                 assert!(update_fail_htlcs.is_empty());
2873                                 assert!(update_fail_malformed_htlcs.is_empty());
2874                         },
2875                         _ => panic!("Unexpected event"),
2876                 }
2877         }
2878         match events[if deliver_bs_raa { 2 } else { 1 }] {
2879                 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, .. } } => {
2880                         assert!(update_add_htlcs.is_empty());
2881                         assert_eq!(update_fail_htlcs.len(), 3);
2882                         assert!(update_fulfill_htlcs.is_empty());
2883                         assert!(update_fail_malformed_htlcs.is_empty());
2884                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2885
2886                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
2887                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
2888                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
2889
2890                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2891
2892                         let events = nodes[0].node.get_and_clear_pending_msg_events();
2893                         // If we delivered B's RAA we got an unknown preimage error, not something
2894                         // that we should update our routing table for.
2895                         assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
2896                         for event in events {
2897                                 match event {
2898                                         MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
2899                                         _ => panic!("Unexpected event"),
2900                                 }
2901                         }
2902                         let events = nodes[0].node.get_and_clear_pending_events();
2903                         assert_eq!(events.len(), 3);
2904                         match events[0] {
2905                                 Event::PaymentFailed { ref payment_hash, .. } => {
2906                                         assert!(failed_htlcs.insert(payment_hash.0));
2907                                 },
2908                                 _ => panic!("Unexpected event"),
2909                         }
2910                         match events[1] {
2911                                 Event::PaymentFailed { ref payment_hash, .. } => {
2912                                         assert!(failed_htlcs.insert(payment_hash.0));
2913                                 },
2914                                 _ => panic!("Unexpected event"),
2915                         }
2916                         match events[2] {
2917                                 Event::PaymentFailed { ref payment_hash, .. } => {
2918                                         assert!(failed_htlcs.insert(payment_hash.0));
2919                                 },
2920                                 _ => panic!("Unexpected event"),
2921                         }
2922                 },
2923                 _ => panic!("Unexpected event"),
2924         }
2925
2926         assert!(failed_htlcs.contains(&first_payment_hash.0));
2927         assert!(failed_htlcs.contains(&second_payment_hash.0));
2928         assert!(failed_htlcs.contains(&third_payment_hash.0));
2929 }
2930
2931 #[test]
2932 fn test_commitment_revoked_fail_backward_exhaustive_a() {
2933         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
2934         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
2935         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
2936         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
2937 }
2938
2939 #[test]
2940 fn test_commitment_revoked_fail_backward_exhaustive_b() {
2941         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
2942         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
2943         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
2944         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
2945 }
2946
2947 #[test]
2948 fn fail_backward_pending_htlc_upon_channel_failure() {
2949         let chanmon_cfgs = create_chanmon_cfgs(2);
2950         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2951         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2952         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2953         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
2954         let logger = Arc::new(test_utils::TestLogger::new());
2955
2956         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
2957         {
2958                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
2959                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
2960                 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &Vec::new(), 50_000, TEST_FINAL_CLTV, logger.clone()).unwrap();
2961                 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
2962                 check_added_monitors!(nodes[0], 1);
2963
2964                 let payment_event = {
2965                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2966                         assert_eq!(events.len(), 1);
2967                         SendEvent::from_event(events.remove(0))
2968                 };
2969                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
2970                 assert_eq!(payment_event.msgs.len(), 1);
2971         }
2972
2973         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
2974         let (_, failed_payment_hash) = get_payment_preimage_hash!(nodes[0]);
2975         {
2976                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
2977                 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &Vec::new(), 50_000, TEST_FINAL_CLTV, logger.clone()).unwrap();
2978                 nodes[0].node.send_payment(&route, failed_payment_hash, &None).unwrap();
2979                 check_added_monitors!(nodes[0], 0);
2980
2981                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2982         }
2983
2984         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
2985         {
2986                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[1]);
2987
2988                 let secp_ctx = Secp256k1::new();
2989                 let session_priv = {
2990                         let mut session_key = [0; 32];
2991                         let mut rng = thread_rng();
2992                         rng.fill_bytes(&mut session_key);
2993                         SecretKey::from_slice(&session_key).expect("RNG is bad!")
2994                 };
2995
2996                 let current_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
2997                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
2998                 let route = get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[0].node.get_our_node_id(), None, &Vec::new(), 50_000, TEST_FINAL_CLTV, logger.clone()).unwrap();
2999                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &None, current_height).unwrap();
3000                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3001                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3002
3003                 // Send a 0-msat update_add_htlc to fail the channel.
3004                 let update_add_htlc = msgs::UpdateAddHTLC {
3005                         channel_id: chan.2,
3006                         htlc_id: 0,
3007                         amount_msat: 0,
3008                         payment_hash,
3009                         cltv_expiry,
3010                         onion_routing_packet,
3011                 };
3012                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3013         }
3014
3015         // Check that Alice fails backward the pending HTLC from the second payment.
3016         expect_payment_failed!(nodes[0], failed_payment_hash, true);
3017         check_closed_broadcast!(nodes[0], true);
3018         check_added_monitors!(nodes[0], 1);
3019 }
3020
3021 #[test]
3022 fn test_htlc_ignore_latest_remote_commitment() {
3023         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3024         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3025         let chanmon_cfgs = create_chanmon_cfgs(2);
3026         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3027         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3028         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3029         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3030
3031         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3032         nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
3033         check_closed_broadcast!(nodes[0], false);
3034         check_added_monitors!(nodes[0], 1);
3035
3036         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3037         assert_eq!(node_txn.len(), 2);
3038
3039         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3040         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3041         check_closed_broadcast!(nodes[1], false);
3042         check_added_monitors!(nodes[1], 1);
3043
3044         // Duplicate the block_connected call since this may happen due to other listeners
3045         // registering new transactions
3046         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3047 }
3048
3049 #[test]
3050 fn test_force_close_fail_back() {
3051         // Check which HTLCs are failed-backwards on channel force-closure
3052         let chanmon_cfgs = create_chanmon_cfgs(3);
3053         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3054         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3055         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3056         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3057         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3058         let logger = Arc::new(test_utils::TestLogger::new());
3059
3060         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3061
3062         let mut payment_event = {
3063                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3064                 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, 42, logger.clone()).unwrap();
3065                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
3066                 check_added_monitors!(nodes[0], 1);
3067
3068                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3069                 assert_eq!(events.len(), 1);
3070                 SendEvent::from_event(events.remove(0))
3071         };
3072
3073         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3074         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3075
3076         expect_pending_htlcs_forwardable!(nodes[1]);
3077
3078         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3079         assert_eq!(events_2.len(), 1);
3080         payment_event = SendEvent::from_event(events_2.remove(0));
3081         assert_eq!(payment_event.msgs.len(), 1);
3082
3083         check_added_monitors!(nodes[1], 1);
3084         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3085         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3086         check_added_monitors!(nodes[2], 1);
3087         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3088
3089         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3090         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3091         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3092
3093         nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
3094         check_closed_broadcast!(nodes[2], false);
3095         check_added_monitors!(nodes[2], 1);
3096         let tx = {
3097                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3098                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3099                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3100                 // back to nodes[1] upon timeout otherwise.
3101                 assert_eq!(node_txn.len(), 1);
3102                 node_txn.remove(0)
3103         };
3104
3105         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3106         nodes[1].block_notifier.block_connected_checked(&header, 1, &[&tx], &[1]);
3107
3108         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3109         check_closed_broadcast!(nodes[1], false);
3110         check_added_monitors!(nodes[1], 1);
3111
3112         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3113         {
3114                 let mut monitors = nodes[2].chan_monitor.simple_monitor.monitors.lock().unwrap();
3115                 monitors.get_mut(&OutPoint::new(Txid::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), 0)).unwrap()
3116                         .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
3117         }
3118         nodes[2].block_notifier.block_connected_checked(&header, 1, &[&tx], &[1]);
3119         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3120         assert_eq!(node_txn.len(), 1);
3121         assert_eq!(node_txn[0].input.len(), 1);
3122         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3123         assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3124         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3125
3126         check_spends!(node_txn[0], tx);
3127 }
3128
3129 #[test]
3130 fn test_unconf_chan() {
3131         // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
3132         let chanmon_cfgs = create_chanmon_cfgs(2);
3133         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3134         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3135         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3136         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3137
3138         let channel_state = nodes[0].node.channel_state.lock().unwrap();
3139         assert_eq!(channel_state.by_id.len(), 1);
3140         assert_eq!(channel_state.short_to_id.len(), 1);
3141         mem::drop(channel_state);
3142
3143         let mut headers = Vec::new();
3144         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3145         headers.push(header.clone());
3146         for _i in 2..100 {
3147                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3148                 headers.push(header.clone());
3149         }
3150         let mut height = 99;
3151         while !headers.is_empty() {
3152                 nodes[0].node.block_disconnected(&headers.pop().unwrap(), height);
3153                 height -= 1;
3154         }
3155         check_closed_broadcast!(nodes[0], false);
3156         check_added_monitors!(nodes[0], 1);
3157         let channel_state = nodes[0].node.channel_state.lock().unwrap();
3158         assert_eq!(channel_state.by_id.len(), 0);
3159         assert_eq!(channel_state.short_to_id.len(), 0);
3160 }
3161
3162 #[test]
3163 fn test_simple_peer_disconnect() {
3164         // Test that we can reconnect when there are no lost messages
3165         let chanmon_cfgs = create_chanmon_cfgs(3);
3166         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3167         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3168         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3169         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3170         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3171
3172         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3173         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3174         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3175
3176         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3177         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3178         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3179         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1, 1_000_000);
3180
3181         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3182         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3183         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3184
3185         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3186         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3187         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3188         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3189
3190         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3191         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3192
3193         claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3, 1_000_000);
3194         fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
3195
3196         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3197         {
3198                 let events = nodes[0].node.get_and_clear_pending_events();
3199                 assert_eq!(events.len(), 2);
3200                 match events[0] {
3201                         Event::PaymentSent { payment_preimage } => {
3202                                 assert_eq!(payment_preimage, payment_preimage_3);
3203                         },
3204                         _ => panic!("Unexpected event"),
3205                 }
3206                 match events[1] {
3207                         Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
3208                                 assert_eq!(payment_hash, payment_hash_5);
3209                                 assert!(rejected_by_dest);
3210                         },
3211                         _ => panic!("Unexpected event"),
3212                 }
3213         }
3214
3215         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4, 1_000_000);
3216         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3217 }
3218
3219 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
3220         // Test that we can reconnect when in-flight HTLC updates get dropped
3221         let chanmon_cfgs = create_chanmon_cfgs(2);
3222         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3223         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3224         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3225         if messages_delivered == 0 {
3226                 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3227                 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3228         } else {
3229                 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3230         }
3231
3232         let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
3233
3234         let logger = Arc::new(test_utils::TestLogger::new());
3235         let payment_event = {
3236                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3237                 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels()), &Vec::new(), 1000000, TEST_FINAL_CLTV, logger.clone()).unwrap();
3238                 nodes[0].node.send_payment(&route, payment_hash_1, &None).unwrap();
3239                 check_added_monitors!(nodes[0], 1);
3240
3241                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3242                 assert_eq!(events.len(), 1);
3243                 SendEvent::from_event(events.remove(0))
3244         };
3245         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3246
3247         if messages_delivered < 2 {
3248                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3249         } else {
3250                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3251                 if messages_delivered >= 3 {
3252                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3253                         check_added_monitors!(nodes[1], 1);
3254                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3255
3256                         if messages_delivered >= 4 {
3257                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3258                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3259                                 check_added_monitors!(nodes[0], 1);
3260
3261                                 if messages_delivered >= 5 {
3262                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3263                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3264                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3265                                         check_added_monitors!(nodes[0], 1);
3266
3267                                         if messages_delivered >= 6 {
3268                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3269                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3270                                                 check_added_monitors!(nodes[1], 1);
3271                                         }
3272                                 }
3273                         }
3274                 }
3275         }
3276
3277         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3278         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3279         if messages_delivered < 3 {
3280                 // Even if the funding_locked messages get exchanged, as long as nothing further was
3281                 // received on either side, both sides will need to resend them.
3282                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
3283         } else if messages_delivered == 3 {
3284                 // nodes[0] still wants its RAA + commitment_signed
3285                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
3286         } else if messages_delivered == 4 {
3287                 // nodes[0] still wants its commitment_signed
3288                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3289         } else if messages_delivered == 5 {
3290                 // nodes[1] still wants its final RAA
3291                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3292         } else if messages_delivered == 6 {
3293                 // Everything was delivered...
3294                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3295         }
3296
3297         let events_1 = nodes[1].node.get_and_clear_pending_events();
3298         assert_eq!(events_1.len(), 1);
3299         match events_1[0] {
3300                 Event::PendingHTLCsForwardable { .. } => { },
3301                 _ => panic!("Unexpected event"),
3302         };
3303
3304         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3305         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3306         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3307
3308         nodes[1].node.process_pending_htlc_forwards();
3309
3310         let events_2 = nodes[1].node.get_and_clear_pending_events();
3311         assert_eq!(events_2.len(), 1);
3312         match events_2[0] {
3313                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
3314                         assert_eq!(payment_hash_1, *payment_hash);
3315                         assert_eq!(*payment_secret, None);
3316                         assert_eq!(amt, 1000000);
3317                 },
3318                 _ => panic!("Unexpected event"),
3319         }
3320
3321         nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000);
3322         check_added_monitors!(nodes[1], 1);
3323
3324         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3325         assert_eq!(events_3.len(), 1);
3326         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3327                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3328                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3329                         assert!(updates.update_add_htlcs.is_empty());
3330                         assert!(updates.update_fail_htlcs.is_empty());
3331                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3332                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3333                         assert!(updates.update_fee.is_none());
3334                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3335                 },
3336                 _ => panic!("Unexpected event"),
3337         };
3338
3339         if messages_delivered >= 1 {
3340                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3341
3342                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3343                 assert_eq!(events_4.len(), 1);
3344                 match events_4[0] {
3345                         Event::PaymentSent { ref payment_preimage } => {
3346                                 assert_eq!(payment_preimage_1, *payment_preimage);
3347                         },
3348                         _ => panic!("Unexpected event"),
3349                 }
3350
3351                 if messages_delivered >= 2 {
3352                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3353                         check_added_monitors!(nodes[0], 1);
3354                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3355
3356                         if messages_delivered >= 3 {
3357                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3358                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3359                                 check_added_monitors!(nodes[1], 1);
3360
3361                                 if messages_delivered >= 4 {
3362                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3363                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3364                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3365                                         check_added_monitors!(nodes[1], 1);
3366
3367                                         if messages_delivered >= 5 {
3368                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3369                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3370                                                 check_added_monitors!(nodes[0], 1);
3371                                         }
3372                                 }
3373                         }
3374                 }
3375         }
3376
3377         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3378         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3379         if messages_delivered < 2 {
3380                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
3381                 //TODO: Deduplicate PaymentSent events, then enable this if:
3382                 //if messages_delivered < 1 {
3383                         let events_4 = nodes[0].node.get_and_clear_pending_events();
3384                         assert_eq!(events_4.len(), 1);
3385                         match events_4[0] {
3386                                 Event::PaymentSent { ref payment_preimage } => {
3387                                         assert_eq!(payment_preimage_1, *payment_preimage);
3388                                 },
3389                                 _ => panic!("Unexpected event"),
3390                         }
3391                 //}
3392         } else if messages_delivered == 2 {
3393                 // nodes[0] still wants its RAA + commitment_signed
3394                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
3395         } else if messages_delivered == 3 {
3396                 // nodes[0] still wants its commitment_signed
3397                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
3398         } else if messages_delivered == 4 {
3399                 // nodes[1] still wants its final RAA
3400                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3401         } else if messages_delivered == 5 {
3402                 // Everything was delivered...
3403                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3404         }
3405
3406         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3407         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3408         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3409
3410         // Channel should still work fine...
3411         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3412         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels()), &Vec::new(), 1000000, TEST_FINAL_CLTV, logger.clone()).unwrap();
3413         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3414         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3415 }
3416
3417 #[test]
3418 fn test_drop_messages_peer_disconnect_a() {
3419         do_test_drop_messages_peer_disconnect(0);
3420         do_test_drop_messages_peer_disconnect(1);
3421         do_test_drop_messages_peer_disconnect(2);
3422         do_test_drop_messages_peer_disconnect(3);
3423 }
3424
3425 #[test]
3426 fn test_drop_messages_peer_disconnect_b() {
3427         do_test_drop_messages_peer_disconnect(4);
3428         do_test_drop_messages_peer_disconnect(5);
3429         do_test_drop_messages_peer_disconnect(6);
3430 }
3431
3432 #[test]
3433 fn test_funding_peer_disconnect() {
3434         // Test that we can lock in our funding tx while disconnected
3435         let chanmon_cfgs = create_chanmon_cfgs(2);
3436         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3437         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3438         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3439         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3440
3441         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3442         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3443
3444         confirm_transaction(&nodes[0].block_notifier, &nodes[0].chain_monitor, &tx, tx.version);
3445         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3446         assert_eq!(events_1.len(), 1);
3447         match events_1[0] {
3448                 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3449                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3450                 },
3451                 _ => panic!("Unexpected event"),
3452         }
3453
3454         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3455
3456         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3457         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3458
3459         confirm_transaction(&nodes[1].block_notifier, &nodes[1].chain_monitor, &tx, tx.version);
3460         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3461         assert_eq!(events_2.len(), 2);
3462         let funding_locked = match events_2[0] {
3463                 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3464                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3465                         msg.clone()
3466                 },
3467                 _ => panic!("Unexpected event"),
3468         };
3469         let bs_announcement_sigs = match events_2[1] {
3470                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3471                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3472                         msg.clone()
3473                 },
3474                 _ => panic!("Unexpected event"),
3475         };
3476
3477         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3478
3479         nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3480         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3481         let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3482         assert_eq!(events_3.len(), 2);
3483         let as_announcement_sigs = match events_3[0] {
3484                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3485                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3486                         msg.clone()
3487                 },
3488                 _ => panic!("Unexpected event"),
3489         };
3490         let (as_announcement, as_update) = match events_3[1] {
3491                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3492                         (msg.clone(), update_msg.clone())
3493                 },
3494                 _ => panic!("Unexpected event"),
3495         };
3496
3497         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3498         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3499         assert_eq!(events_4.len(), 1);
3500         let (_, bs_update) = match events_4[0] {
3501                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3502                         (msg.clone(), update_msg.clone())
3503                 },
3504                 _ => panic!("Unexpected event"),
3505         };
3506
3507         nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3508         nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3509         nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3510
3511         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3512         let logger = Arc::new(test_utils::TestLogger::new());
3513         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, logger.clone()).unwrap();
3514         let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3515         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage, 1_000_000);
3516 }
3517
3518 #[test]
3519 fn test_drop_messages_peer_disconnect_dual_htlc() {
3520         // Test that we can handle reconnecting when both sides of a channel have pending
3521         // commitment_updates when we disconnect.
3522         let chanmon_cfgs = create_chanmon_cfgs(2);
3523         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3524         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3525         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3526         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3527         let logger = Arc::new(test_utils::TestLogger::new());
3528
3529         let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3530
3531         // Now try to send a second payment which will fail to send
3532         let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
3533         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3534         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, logger.clone()).unwrap();
3535         nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
3536         check_added_monitors!(nodes[0], 1);
3537
3538         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3539         assert_eq!(events_1.len(), 1);
3540         match events_1[0] {
3541                 MessageSendEvent::UpdateHTLCs { .. } => {},
3542                 _ => panic!("Unexpected event"),
3543         }
3544
3545         assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000));
3546         check_added_monitors!(nodes[1], 1);
3547
3548         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3549         assert_eq!(events_2.len(), 1);
3550         match events_2[0] {
3551                 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 } } => {
3552                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3553                         assert!(update_add_htlcs.is_empty());
3554                         assert_eq!(update_fulfill_htlcs.len(), 1);
3555                         assert!(update_fail_htlcs.is_empty());
3556                         assert!(update_fail_malformed_htlcs.is_empty());
3557                         assert!(update_fee.is_none());
3558
3559                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3560                         let events_3 = nodes[0].node.get_and_clear_pending_events();
3561                         assert_eq!(events_3.len(), 1);
3562                         match events_3[0] {
3563                                 Event::PaymentSent { ref payment_preimage } => {
3564                                         assert_eq!(*payment_preimage, payment_preimage_1);
3565                                 },
3566                                 _ => panic!("Unexpected event"),
3567                         }
3568
3569                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3570                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3571                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3572                         check_added_monitors!(nodes[0], 1);
3573                 },
3574                 _ => panic!("Unexpected event"),
3575         }
3576
3577         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3578         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3579
3580         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3581         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3582         assert_eq!(reestablish_1.len(), 1);
3583         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3584         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3585         assert_eq!(reestablish_2.len(), 1);
3586
3587         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3588         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3589         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3590         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3591
3592         assert!(as_resp.0.is_none());
3593         assert!(bs_resp.0.is_none());
3594
3595         assert!(bs_resp.1.is_none());
3596         assert!(bs_resp.2.is_none());
3597
3598         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3599
3600         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3601         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3602         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3603         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3604         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3605         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
3606         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
3607         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3608         // No commitment_signed so get_event_msg's assert(len == 1) passes
3609         check_added_monitors!(nodes[1], 1);
3610
3611         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
3612         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3613         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3614         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3615         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3616         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3617         assert!(bs_second_commitment_signed.update_fee.is_none());
3618         check_added_monitors!(nodes[1], 1);
3619
3620         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3621         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3622         assert!(as_commitment_signed.update_add_htlcs.is_empty());
3623         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
3624         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
3625         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
3626         assert!(as_commitment_signed.update_fee.is_none());
3627         check_added_monitors!(nodes[0], 1);
3628
3629         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
3630         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3631         // No commitment_signed so get_event_msg's assert(len == 1) passes
3632         check_added_monitors!(nodes[0], 1);
3633
3634         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
3635         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3636         // No commitment_signed so get_event_msg's assert(len == 1) passes
3637         check_added_monitors!(nodes[1], 1);
3638
3639         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3640         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3641         check_added_monitors!(nodes[1], 1);
3642
3643         expect_pending_htlcs_forwardable!(nodes[1]);
3644
3645         let events_5 = nodes[1].node.get_and_clear_pending_events();
3646         assert_eq!(events_5.len(), 1);
3647         match events_5[0] {
3648                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt: _ } => {
3649                         assert_eq!(payment_hash_2, *payment_hash);
3650                         assert_eq!(*payment_secret, None);
3651                 },
3652                 _ => panic!("Unexpected event"),
3653         }
3654
3655         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
3656         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3657         check_added_monitors!(nodes[0], 1);
3658
3659         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3660 }
3661
3662 fn do_test_htlc_timeout(send_partial_mpp: bool) {
3663         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
3664         // to avoid our counterparty failing the channel.
3665         let chanmon_cfgs = create_chanmon_cfgs(2);
3666         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3667         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3668         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3669
3670         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3671         let logger = Arc::new(test_utils::TestLogger::new());
3672
3673         let our_payment_hash = if send_partial_mpp {
3674                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3675                 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, logger.clone()).unwrap();
3676                 let (_, our_payment_hash) = get_payment_preimage_hash!(&nodes[0]);
3677                 let payment_secret = PaymentSecret([0xdb; 32]);
3678                 // Use the utility function send_payment_along_path to send the payment with MPP data which
3679                 // indicates there are more HTLCs coming.
3680                 nodes[0].node.send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200000, CHAN_CONFIRM_DEPTH).unwrap();
3681                 check_added_monitors!(nodes[0], 1);
3682                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3683                 assert_eq!(events.len(), 1);
3684                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
3685                 // hop should *not* yet generate any PaymentReceived event(s).
3686                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false);
3687                 our_payment_hash
3688         } else {
3689                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
3690         };
3691
3692         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3693         nodes[0].block_notifier.block_connected_checked(&header, 101, &[], &[]);
3694         nodes[1].block_notifier.block_connected_checked(&header, 101, &[], &[]);
3695         for i in 102..TEST_FINAL_CLTV + 100 + 1 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
3696                 header.prev_blockhash = header.bitcoin_hash();
3697                 nodes[0].block_notifier.block_connected_checked(&header, i, &[], &[]);
3698                 nodes[1].block_notifier.block_connected_checked(&header, i, &[], &[]);
3699         }
3700
3701         expect_pending_htlcs_forwardable!(nodes[1]);
3702
3703         check_added_monitors!(nodes[1], 1);
3704         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3705         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
3706         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
3707         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
3708         assert!(htlc_timeout_updates.update_fee.is_none());
3709
3710         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
3711         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
3712         // 100_000 msat as u64, followed by a height of 123 as u32
3713         let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
3714         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(123));
3715         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
3716 }
3717
3718 #[test]
3719 fn test_htlc_timeout() {
3720         do_test_htlc_timeout(true);
3721         do_test_htlc_timeout(false);
3722 }
3723
3724 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
3725         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
3726         let chanmon_cfgs = create_chanmon_cfgs(3);
3727         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3728         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3729         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3730         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3731         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3732         let logger = Arc::new(test_utils::TestLogger::new());
3733
3734         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
3735         let (_, first_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3736         {
3737                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3738                 let route = get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, logger.clone()).unwrap();
3739                 nodes[1].node.send_payment(&route, first_payment_hash, &None).unwrap();
3740         }
3741         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
3742         check_added_monitors!(nodes[1], 1);
3743
3744         // Now attempt to route a second payment, which should be placed in the holding cell
3745         let (_, second_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3746         if forwarded_htlc {
3747                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3748                 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, logger.clone()).unwrap();
3749                 nodes[0].node.send_payment(&route, second_payment_hash, &None).unwrap();
3750                 check_added_monitors!(nodes[0], 1);
3751                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
3752                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3753                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3754                 expect_pending_htlcs_forwardable!(nodes[1]);
3755                 check_added_monitors!(nodes[1], 0);
3756         } else {
3757                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3758                 let route = get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, logger.clone()).unwrap();
3759                 nodes[1].node.send_payment(&route, second_payment_hash, &None).unwrap();
3760                 check_added_monitors!(nodes[1], 0);
3761         }
3762
3763         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3764         nodes[1].block_notifier.block_connected_checked(&header, 101, &[], &[]);
3765         for i in 102..TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
3766                 header.prev_blockhash = header.bitcoin_hash();
3767                 nodes[1].block_notifier.block_connected_checked(&header, i, &[], &[]);
3768         }
3769
3770         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3771         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3772
3773         header.prev_blockhash = header.bitcoin_hash();
3774         nodes[1].block_notifier.block_connected_checked(&header, TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS, &[], &[]);
3775
3776         if forwarded_htlc {
3777                 expect_pending_htlcs_forwardable!(nodes[1]);
3778                 check_added_monitors!(nodes[1], 1);
3779                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
3780                 assert_eq!(fail_commit.len(), 1);
3781                 match fail_commit[0] {
3782                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
3783                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3784                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
3785                         },
3786                         _ => unreachable!(),
3787                 }
3788                 expect_payment_failed!(nodes[0], second_payment_hash, false);
3789                 if let &MessageSendEvent::PaymentFailureNetworkUpdate { ref update } = &nodes[0].node.get_and_clear_pending_msg_events()[0] {
3790                         match update {
3791                                 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {},
3792                                 _ => panic!("Unexpected event"),
3793                         }
3794                 } else {
3795                         panic!("Unexpected event");
3796                 }
3797         } else {
3798                 expect_payment_failed!(nodes[1], second_payment_hash, true);
3799         }
3800 }
3801
3802 #[test]
3803 fn test_holding_cell_htlc_add_timeouts() {
3804         do_test_holding_cell_htlc_add_timeouts(false);
3805         do_test_holding_cell_htlc_add_timeouts(true);
3806 }
3807
3808 #[test]
3809 fn test_invalid_channel_announcement() {
3810         //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
3811         let secp_ctx = Secp256k1::new();
3812         let chanmon_cfgs = create_chanmon_cfgs(2);
3813         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3814         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3815         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3816
3817         let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
3818
3819         let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
3820         let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
3821         let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
3822         let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
3823
3824         nodes[0].net_graph_msg_handler.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id : as_chan.get_short_channel_id().unwrap(), is_permanent: false } );
3825
3826         let as_bitcoin_key = as_chan.get_local_keys().inner.local_channel_pubkeys.funding_pubkey;
3827         let bs_bitcoin_key = bs_chan.get_local_keys().inner.local_channel_pubkeys.funding_pubkey;
3828
3829         let as_network_key = nodes[0].node.get_our_node_id();
3830         let bs_network_key = nodes[1].node.get_our_node_id();
3831
3832         let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
3833
3834         let mut chan_announcement;
3835
3836         macro_rules! dummy_unsigned_msg {
3837                 () => {
3838                         msgs::UnsignedChannelAnnouncement {
3839                                 features: ChannelFeatures::known(),
3840                                 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
3841                                 short_channel_id: as_chan.get_short_channel_id().unwrap(),
3842                                 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
3843                                 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
3844                                 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
3845                                 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
3846                                 excess_data: Vec::new(),
3847                         };
3848                 }
3849         }
3850
3851         macro_rules! sign_msg {
3852                 ($unsigned_msg: expr) => {
3853                         let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
3854                         let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_local_keys().inner.funding_key());
3855                         let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_local_keys().inner.funding_key());
3856                         let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
3857                         let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
3858                         chan_announcement = msgs::ChannelAnnouncement {
3859                                 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
3860                                 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
3861                                 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
3862                                 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
3863                                 contents: $unsigned_msg
3864                         }
3865                 }
3866         }
3867
3868         let unsigned_msg = dummy_unsigned_msg!();
3869         sign_msg!(unsigned_msg);
3870         assert_eq!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap(), true);
3871         let _ = nodes[0].net_graph_msg_handler.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id : as_chan.get_short_channel_id().unwrap(), is_permanent: false } );
3872
3873         // Configured with Network::Testnet
3874         let mut unsigned_msg = dummy_unsigned_msg!();
3875         unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.bitcoin_hash();
3876         sign_msg!(unsigned_msg);
3877         assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
3878
3879         let mut unsigned_msg = dummy_unsigned_msg!();
3880         unsigned_msg.chain_hash = BlockHash::hash(&[1,2,3,4,5,6,7,8,9]);
3881         sign_msg!(unsigned_msg);
3882         assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
3883 }
3884
3885 #[test]
3886 fn test_no_txn_manager_serialize_deserialize() {
3887         let chanmon_cfgs = create_chanmon_cfgs(2);
3888         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3889         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3890         let fee_estimator: test_utils::TestFeeEstimator;
3891         let new_chan_monitor: test_utils::TestChannelMonitor;
3892         let keys_manager: test_utils::TestKeysInterface;
3893         let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>;
3894         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3895
3896         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3897
3898         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3899
3900         let nodes_0_serialized = nodes[0].node.encode();
3901         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3902         nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
3903
3904         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
3905         new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), Arc::new(test_utils::TestLogger::new()), &fee_estimator);
3906         nodes[0].chan_monitor = &new_chan_monitor;
3907         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3908         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
3909         assert!(chan_0_monitor_read.is_empty());
3910
3911         let mut nodes_0_read = &nodes_0_serialized[..];
3912         let config = UserConfig::default();
3913         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new()));
3914         let (_, nodes_0_deserialized_tmp) = {
3915                 let mut channel_monitors = HashMap::new();
3916                 channel_monitors.insert(chan_0_monitor.get_funding_txo(), &mut chan_0_monitor);
3917                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3918                         default_config: config,
3919                         keys_manager: &keys_manager,
3920                         fee_estimator: &fee_estimator,
3921                         monitor: nodes[0].chan_monitor,
3922                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3923                         logger: Arc::new(test_utils::TestLogger::new()),
3924                         channel_monitors: &mut channel_monitors,
3925                 }).unwrap()
3926         };
3927         nodes_0_deserialized = nodes_0_deserialized_tmp;
3928         assert!(nodes_0_read.is_empty());
3929
3930         assert!(nodes[0].chan_monitor.add_monitor(chan_0_monitor.get_funding_txo(), chan_0_monitor).is_ok());
3931         nodes[0].node = &nodes_0_deserialized;
3932         nodes[0].block_notifier.register_listener(nodes[0].node);
3933         assert_eq!(nodes[0].node.list_channels().len(), 1);
3934         check_added_monitors!(nodes[0], 1);
3935
3936         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3937         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3938         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3939         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3940
3941         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3942         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3943         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3944         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3945
3946         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
3947         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
3948         for node in nodes.iter() {
3949                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
3950                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3951                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3952         }
3953
3954         send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
3955 }
3956
3957 #[test]
3958 fn test_simple_manager_serialize_deserialize() {
3959         let chanmon_cfgs = create_chanmon_cfgs(2);
3960         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3961         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3962         let fee_estimator: test_utils::TestFeeEstimator;
3963         let new_chan_monitor: test_utils::TestChannelMonitor;
3964         let keys_manager: test_utils::TestKeysInterface;
3965         let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>;
3966         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3967         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3968
3969         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3970         let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3971
3972         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3973
3974         let nodes_0_serialized = nodes[0].node.encode();
3975         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3976         nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
3977
3978         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
3979         new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), Arc::new(test_utils::TestLogger::new()), &fee_estimator);
3980         nodes[0].chan_monitor = &new_chan_monitor;
3981         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3982         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
3983         assert!(chan_0_monitor_read.is_empty());
3984
3985         let mut nodes_0_read = &nodes_0_serialized[..];
3986         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new()));
3987         let (_, nodes_0_deserialized_tmp) = {
3988                 let mut channel_monitors = HashMap::new();
3989                 channel_monitors.insert(chan_0_monitor.get_funding_txo(), &mut chan_0_monitor);
3990                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3991                         default_config: UserConfig::default(),
3992                         keys_manager: &keys_manager,
3993                         fee_estimator: &fee_estimator,
3994                         monitor: nodes[0].chan_monitor,
3995                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3996                         logger: Arc::new(test_utils::TestLogger::new()),
3997                         channel_monitors: &mut channel_monitors,
3998                 }).unwrap()
3999         };
4000         nodes_0_deserialized = nodes_0_deserialized_tmp;
4001         assert!(nodes_0_read.is_empty());
4002
4003         assert!(nodes[0].chan_monitor.add_monitor(chan_0_monitor.get_funding_txo(), chan_0_monitor).is_ok());
4004         nodes[0].node = &nodes_0_deserialized;
4005         check_added_monitors!(nodes[0], 1);
4006
4007         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4008
4009         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4010         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage, 1_000_000);
4011 }
4012
4013 #[test]
4014 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4015         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4016         let chanmon_cfgs = create_chanmon_cfgs(4);
4017         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4018         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4019         let fee_estimator: test_utils::TestFeeEstimator;
4020         let new_chan_monitor: test_utils::TestChannelMonitor;
4021         let keys_manager: test_utils::TestKeysInterface;
4022         let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>;
4023         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4024         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4025         create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known());
4026         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4027
4028         let mut node_0_stale_monitors_serialized = Vec::new();
4029         for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
4030                 let mut writer = test_utils::TestVecWriter(Vec::new());
4031                 monitor.1.write_for_disk(&mut writer).unwrap();
4032                 node_0_stale_monitors_serialized.push(writer.0);
4033         }
4034
4035         let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4036
4037         // Serialize the ChannelManager here, but the monitor we keep up-to-date
4038         let nodes_0_serialized = nodes[0].node.encode();
4039
4040         route_payment(&nodes[0], &[&nodes[3]], 1000000);
4041         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4042         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4043         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4044
4045         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4046         // nodes[3])
4047         let mut node_0_monitors_serialized = Vec::new();
4048         for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
4049                 let mut writer = test_utils::TestVecWriter(Vec::new());
4050                 monitor.1.write_for_disk(&mut writer).unwrap();
4051                 node_0_monitors_serialized.push(writer.0);
4052         }
4053
4054         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4055         new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), Arc::new(test_utils::TestLogger::new()), &fee_estimator);
4056         nodes[0].chan_monitor = &new_chan_monitor;
4057
4058         let mut node_0_stale_monitors = Vec::new();
4059         for serialized in node_0_stale_monitors_serialized.iter() {
4060                 let mut read = &serialized[..];
4061                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read, Arc::new(test_utils::TestLogger::new())).unwrap();
4062                 assert!(read.is_empty());
4063                 node_0_stale_monitors.push(monitor);
4064         }
4065
4066         let mut node_0_monitors = Vec::new();
4067         for serialized in node_0_monitors_serialized.iter() {
4068                 let mut read = &serialized[..];
4069                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read, Arc::new(test_utils::TestLogger::new())).unwrap();
4070                 assert!(read.is_empty());
4071                 node_0_monitors.push(monitor);
4072         }
4073
4074         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new()));
4075
4076         let mut nodes_0_read = &nodes_0_serialized[..];
4077         if let Err(msgs::DecodeError::InvalidValue) =
4078                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4079                 default_config: UserConfig::default(),
4080                 keys_manager: &keys_manager,
4081                 fee_estimator: &fee_estimator,
4082                 monitor: nodes[0].chan_monitor,
4083                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4084                 logger: Arc::new(test_utils::TestLogger::new()),
4085                 channel_monitors: &mut node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo(), monitor) }).collect(),
4086         }) { } else {
4087                 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4088         };
4089
4090         let mut nodes_0_read = &nodes_0_serialized[..];
4091         let (_, nodes_0_deserialized_tmp) =
4092                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4093                 default_config: UserConfig::default(),
4094                 keys_manager: &keys_manager,
4095                 fee_estimator: &fee_estimator,
4096                 monitor: nodes[0].chan_monitor,
4097                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4098                 logger: Arc::new(test_utils::TestLogger::new()),
4099                 channel_monitors: &mut node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo(), monitor) }).collect(),
4100         }).unwrap();
4101         nodes_0_deserialized = nodes_0_deserialized_tmp;
4102         assert!(nodes_0_read.is_empty());
4103
4104         { // Channel close should result in a commitment tx and an HTLC tx
4105                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4106                 assert_eq!(txn.len(), 2);
4107                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4108                 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
4109         }
4110
4111         for monitor in node_0_monitors.drain(..) {
4112                 assert!(nodes[0].chan_monitor.add_monitor(monitor.get_funding_txo(), monitor).is_ok());
4113                 check_added_monitors!(nodes[0], 1);
4114         }
4115         nodes[0].node = &nodes_0_deserialized;
4116
4117         // nodes[1] and nodes[2] have no lost state with nodes[0]...
4118         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4119         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4120         //... and we can even still claim the payment!
4121         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage, 1_000_000);
4122
4123         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4124         let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4125         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4126         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4127         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4128         assert_eq!(msg_events.len(), 1);
4129         if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4130                 match action {
4131                         &ErrorAction::SendErrorMessage { ref msg } => {
4132                                 assert_eq!(msg.channel_id, channel_id);
4133                         },
4134                         _ => panic!("Unexpected event!"),
4135                 }
4136         }
4137 }
4138
4139 macro_rules! check_spendable_outputs {
4140         ($node: expr, $der_idx: expr) => {
4141                 {
4142                         let events = $node.chan_monitor.simple_monitor.get_and_clear_pending_events();
4143                         let mut txn = Vec::new();
4144                         for event in events {
4145                                 match event {
4146                                         Event::SpendableOutputs { ref outputs } => {
4147                                                 for outp in outputs {
4148                                                         match *outp {
4149                                                                 SpendableOutputDescriptor::DynamicOutputP2WPKH { ref outpoint, ref key, ref output } => {
4150                                                                         let input = TxIn {
4151                                                                                 previous_output: outpoint.clone(),
4152                                                                                 script_sig: Script::new(),
4153                                                                                 sequence: 0,
4154                                                                                 witness: Vec::new(),
4155                                                                         };
4156                                                                         let outp = TxOut {
4157                                                                                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4158                                                                                 value: output.value,
4159                                                                         };
4160                                                                         let mut spend_tx = Transaction {
4161                                                                                 version: 2,
4162                                                                                 lock_time: 0,
4163                                                                                 input: vec![input],
4164                                                                                 output: vec![outp],
4165                                                                         };
4166                                                                         let secp_ctx = Secp256k1::new();
4167                                                                         let remotepubkey = PublicKey::from_secret_key(&secp_ctx, &key);
4168                                                                         let witness_script = Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: remotepubkey}, Network::Testnet).script_pubkey();
4169                                                                         let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
4170                                                                         let remotesig = secp_ctx.sign(&sighash, key);
4171                                                                         spend_tx.input[0].witness.push(remotesig.serialize_der().to_vec());
4172                                                                         spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4173                                                                         spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
4174                                                                         txn.push(spend_tx);
4175                                                                 },
4176                                                                 SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref key, ref witness_script, ref to_self_delay, ref output } => {
4177                                                                         let input = TxIn {
4178                                                                                 previous_output: outpoint.clone(),
4179                                                                                 script_sig: Script::new(),
4180                                                                                 sequence: *to_self_delay as u32,
4181                                                                                 witness: Vec::new(),
4182                                                                         };
4183                                                                         let outp = TxOut {
4184                                                                                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4185                                                                                 value: output.value,
4186                                                                         };
4187                                                                         let mut spend_tx = Transaction {
4188                                                                                 version: 2,
4189                                                                                 lock_time: 0,
4190                                                                                 input: vec![input],
4191                                                                                 output: vec![outp],
4192                                                                         };
4193                                                                         let secp_ctx = Secp256k1::new();
4194                                                                         let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], witness_script, output.value)[..]).unwrap();
4195                                                                         let local_delaysig = secp_ctx.sign(&sighash, key);
4196                                                                         spend_tx.input[0].witness.push(local_delaysig.serialize_der().to_vec());
4197                                                                         spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4198                                                                         spend_tx.input[0].witness.push(vec!());
4199                                                                         spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
4200                                                                         txn.push(spend_tx);
4201                                                                 },
4202                                                                 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
4203                                                                         let secp_ctx = Secp256k1::new();
4204                                                                         let input = TxIn {
4205                                                                                 previous_output: outpoint.clone(),
4206                                                                                 script_sig: Script::new(),
4207                                                                                 sequence: 0,
4208                                                                                 witness: Vec::new(),
4209                                                                         };
4210                                                                         let outp = TxOut {
4211                                                                                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4212                                                                                 value: output.value,
4213                                                                         };
4214                                                                         let mut spend_tx = Transaction {
4215                                                                                 version: 2,
4216                                                                                 lock_time: 0,
4217                                                                                 input: vec![input],
4218                                                                                 output: vec![outp.clone()],
4219                                                                         };
4220                                                                         let secret = {
4221                                                                                 match ExtendedPrivKey::new_master(Network::Testnet, &$node.node_seed) {
4222                                                                                         Ok(master_key) => {
4223                                                                                                 match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx).expect("key space exhausted")) {
4224                                                                                                         Ok(key) => key,
4225                                                                                                         Err(_) => panic!("Your RNG is busted"),
4226                                                                                                 }
4227                                                                                         }
4228                                                                                         Err(_) => panic!("Your rng is busted"),
4229                                                                                 }
4230                                                                         };
4231                                                                         let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
4232                                                                         let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
4233                                                                         let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
4234                                                                         let sig = secp_ctx.sign(&sighash, &secret.private_key.key);
4235                                                                         spend_tx.input[0].witness.push(sig.serialize_der().to_vec());
4236                                                                         spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4237                                                                         spend_tx.input[0].witness.push(pubkey.key.serialize().to_vec());
4238                                                                         txn.push(spend_tx);
4239                                                                 },
4240                                                         }
4241                                                 }
4242                                         },
4243                                         _ => panic!("Unexpected event"),
4244                                 };
4245                         }
4246                         txn
4247                 }
4248         }
4249 }
4250
4251 #[test]
4252 fn test_claim_sizeable_push_msat() {
4253         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4254         let chanmon_cfgs = create_chanmon_cfgs(2);
4255         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4256         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4257         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4258
4259         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4260         nodes[1].node.force_close_channel(&chan.2);
4261         check_closed_broadcast!(nodes[1], false);
4262         check_added_monitors!(nodes[1], 1);
4263         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4264         assert_eq!(node_txn.len(), 1);
4265         check_spends!(node_txn[0], chan.3);
4266         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
4267
4268         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4269         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4270         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4271
4272         let spend_txn = check_spendable_outputs!(nodes[1], 1);
4273         assert_eq!(spend_txn.len(), 1);
4274         check_spends!(spend_txn[0], node_txn[0]);
4275 }
4276
4277 #[test]
4278 fn test_claim_on_remote_sizeable_push_msat() {
4279         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4280         // to_remote output is encumbered by a P2WPKH
4281         let chanmon_cfgs = create_chanmon_cfgs(2);
4282         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4283         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4284         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4285
4286         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4287         nodes[0].node.force_close_channel(&chan.2);
4288         check_closed_broadcast!(nodes[0], false);
4289         check_added_monitors!(nodes[0], 1);
4290
4291         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4292         assert_eq!(node_txn.len(), 1);
4293         check_spends!(node_txn[0], chan.3);
4294         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
4295
4296         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4297         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4298         check_closed_broadcast!(nodes[1], false);
4299         check_added_monitors!(nodes[1], 1);
4300         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4301
4302         let spend_txn = check_spendable_outputs!(nodes[1], 1);
4303         assert_eq!(spend_txn.len(), 2);
4304         assert_eq!(spend_txn[0], spend_txn[1]);
4305         check_spends!(spend_txn[0], node_txn[0]);
4306 }
4307
4308 #[test]
4309 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4310         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4311         // to_remote output is encumbered by a P2WPKH
4312
4313         let chanmon_cfgs = create_chanmon_cfgs(2);
4314         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4315         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4316         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4317
4318         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4319         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4320         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4321         assert_eq!(revoked_local_txn[0].input.len(), 1);
4322         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4323
4324         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4325         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4326         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
4327         check_closed_broadcast!(nodes[1], false);
4328         check_added_monitors!(nodes[1], 1);
4329
4330         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4331         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4332         nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4333         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4334
4335         let spend_txn = check_spendable_outputs!(nodes[1], 1);
4336         assert_eq!(spend_txn.len(), 3);
4337         assert_eq!(spend_txn[0], spend_txn[1]); // to_remote output on revoked remote commitment_tx
4338         check_spends!(spend_txn[0], revoked_local_txn[0]);
4339         check_spends!(spend_txn[2], node_txn[0]);
4340 }
4341
4342 #[test]
4343 fn test_static_spendable_outputs_preimage_tx() {
4344         let chanmon_cfgs = create_chanmon_cfgs(2);
4345         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4346         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4347         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4348
4349         // Create some initial channels
4350         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4351
4352         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4353
4354         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4355         assert_eq!(commitment_tx[0].input.len(), 1);
4356         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4357
4358         // Settle A's commitment tx on B's chain
4359         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4360         assert!(nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000));
4361         check_added_monitors!(nodes[1], 1);
4362         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
4363         check_added_monitors!(nodes[1], 1);
4364         let events = nodes[1].node.get_and_clear_pending_msg_events();
4365         match events[0] {
4366                 MessageSendEvent::UpdateHTLCs { .. } => {},
4367                 _ => panic!("Unexpected event"),
4368         }
4369         match events[1] {
4370                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4371                 _ => panic!("Unexepected event"),
4372         }
4373
4374         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4375         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4376         assert_eq!(node_txn.len(), 3);
4377         check_spends!(node_txn[0], commitment_tx[0]);
4378         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4379         check_spends!(node_txn[1], chan_1.3);
4380         check_spends!(node_txn[2], node_txn[1]);
4381
4382         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4383         nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4384         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4385
4386         let spend_txn = check_spendable_outputs!(nodes[1], 1);
4387         assert_eq!(spend_txn.len(), 1);
4388         check_spends!(spend_txn[0], node_txn[0]);
4389 }
4390
4391 #[test]
4392 fn test_static_spendable_outputs_timeout_tx() {
4393         let chanmon_cfgs = create_chanmon_cfgs(2);
4394         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4395         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4396         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4397
4398         // Create some initial channels
4399         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4400
4401         // Rebalance the network a bit by relaying one payment through all the channels ...
4402         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
4403
4404         let (_, our_payment_hash) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4405
4406         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4407         assert_eq!(commitment_tx[0].input.len(), 1);
4408         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4409
4410         // Settle A's commitment tx on B' chain
4411         let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
4412         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 0);
4413         check_added_monitors!(nodes[1], 1);
4414         let events = nodes[1].node.get_and_clear_pending_msg_events();
4415         match events[0] {
4416                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4417                 _ => panic!("Unexpected event"),
4418         }
4419
4420         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4421         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4422         assert_eq!(node_txn.len(), 3); // ChannelManager : 2 (local commitent tx + HTLC-timeout), ChannelMonitor: timeout tx
4423         check_spends!(node_txn[0],  commitment_tx[0].clone());
4424         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4425         check_spends!(node_txn[1], chan_1.3.clone());
4426         check_spends!(node_txn[2], node_txn[1]);
4427
4428         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4429         nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4430         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4431         expect_payment_failed!(nodes[1], our_payment_hash, true);
4432
4433         let spend_txn = check_spendable_outputs!(nodes[1], 1);
4434         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote (*2), timeout_tx.output (*1)
4435         check_spends!(spend_txn[2], node_txn[0].clone());
4436 }
4437
4438 #[test]
4439 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4440         let chanmon_cfgs = create_chanmon_cfgs(2);
4441         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4442         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4443         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4444
4445         // Create some initial channels
4446         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4447
4448         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4449         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4450         assert_eq!(revoked_local_txn[0].input.len(), 1);
4451         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4452
4453         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4454
4455         let  header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4456         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
4457         check_closed_broadcast!(nodes[1], false);
4458         check_added_monitors!(nodes[1], 1);
4459
4460         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4461         assert_eq!(node_txn.len(), 2);
4462         assert_eq!(node_txn[0].input.len(), 2);
4463         check_spends!(node_txn[0], revoked_local_txn[0]);
4464
4465         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4466         nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4467         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4468
4469         let spend_txn = check_spendable_outputs!(nodes[1], 1);
4470         assert_eq!(spend_txn.len(), 1);
4471         check_spends!(spend_txn[0], node_txn[0]);
4472 }
4473
4474 #[test]
4475 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4476         let chanmon_cfgs = create_chanmon_cfgs(2);
4477         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4478         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4479         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4480
4481         // Create some initial channels
4482         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4483
4484         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4485         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4486         assert_eq!(revoked_local_txn[0].input.len(), 1);
4487         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4488
4489         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4490
4491         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4492         // A will generate HTLC-Timeout from revoked commitment tx
4493         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4494         check_closed_broadcast!(nodes[0], false);
4495         check_added_monitors!(nodes[0], 1);
4496
4497         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4498         assert_eq!(revoked_htlc_txn.len(), 2);
4499         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4500         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4501         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4502         check_spends!(revoked_htlc_txn[1], chan_1.3);
4503
4504         // B will generate justice tx from A's revoked commitment/HTLC tx
4505         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 0);
4506         check_closed_broadcast!(nodes[1], false);
4507         check_added_monitors!(nodes[1], 1);
4508
4509         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4510         assert_eq!(node_txn.len(), 4); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-timeout, adjusted justice tx, ChannelManager: local commitment tx
4511         assert_eq!(node_txn[0].input.len(), 2);
4512         check_spends!(node_txn[0], revoked_local_txn[0]);
4513         check_spends!(node_txn[1], chan_1.3);
4514         assert_eq!(node_txn[2].input.len(), 1);
4515         check_spends!(node_txn[2], revoked_htlc_txn[0]);
4516         assert_eq!(node_txn[3].input.len(), 1);
4517         check_spends!(node_txn[3], revoked_local_txn[0]);
4518
4519         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4520         nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone(), node_txn[2].clone()] }, 1);
4521         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4522
4523         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4524         let spend_txn = check_spendable_outputs!(nodes[1], 1);
4525         assert_eq!(spend_txn.len(), 2);
4526         check_spends!(spend_txn[0], node_txn[0]);
4527         check_spends!(spend_txn[1], node_txn[2]);
4528 }
4529
4530 #[test]
4531 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4532         let chanmon_cfgs = create_chanmon_cfgs(2);
4533         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4534         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4535         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4536
4537         // Create some initial channels
4538         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4539
4540         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4541         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4542         assert_eq!(revoked_local_txn[0].input.len(), 1);
4543         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4544
4545         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4546
4547         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4548         // B will generate HTLC-Success from revoked commitment tx
4549         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4550         check_closed_broadcast!(nodes[1], false);
4551         check_added_monitors!(nodes[1], 1);
4552         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4553
4554         assert_eq!(revoked_htlc_txn.len(), 2);
4555         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4556         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4557         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4558
4559         // A will generate justice tx from B's revoked commitment/HTLC tx
4560         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
4561         check_closed_broadcast!(nodes[0], false);
4562         check_added_monitors!(nodes[0], 1);
4563
4564         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4565         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
4566         assert_eq!(node_txn[2].input.len(), 1);
4567         check_spends!(node_txn[2], revoked_htlc_txn[0]);
4568
4569         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4570         nodes[0].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone(), node_txn[2].clone()] }, 1);
4571         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4572
4573         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4574         let spend_txn = check_spendable_outputs!(nodes[0], 1);
4575         assert_eq!(spend_txn.len(), 5); // Duplicated SpendableOutput due to block rescan after revoked htlc output tracking
4576         assert_eq!(spend_txn[0], spend_txn[1]);
4577         assert_eq!(spend_txn[0], spend_txn[2]);
4578         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4579         check_spends!(spend_txn[3], node_txn[0]); // spending justice tx output from revoked local tx htlc received output
4580         check_spends!(spend_txn[4], node_txn[2]); // spending justice tx output on htlc success tx
4581 }
4582
4583 #[test]
4584 fn test_onchain_to_onchain_claim() {
4585         // Test that in case of channel closure, we detect the state of output thanks to
4586         // ChainWatchInterface and claim HTLC on downstream peer's remote commitment tx.
4587         // First, have C claim an HTLC against its own latest commitment transaction.
4588         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4589         // channel.
4590         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4591         // gets broadcast.
4592
4593         let chanmon_cfgs = create_chanmon_cfgs(3);
4594         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4595         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4596         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4597
4598         // Create some initial channels
4599         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4600         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4601
4602         // Rebalance the network a bit by relaying one payment through all the channels ...
4603         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
4604         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
4605
4606         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
4607         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
4608         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4609         check_spends!(commitment_tx[0], chan_2.3);
4610         nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000);
4611         check_added_monitors!(nodes[2], 1);
4612         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4613         assert!(updates.update_add_htlcs.is_empty());
4614         assert!(updates.update_fail_htlcs.is_empty());
4615         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4616         assert!(updates.update_fail_malformed_htlcs.is_empty());
4617
4618         nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
4619         check_closed_broadcast!(nodes[2], false);
4620         check_added_monitors!(nodes[2], 1);
4621
4622         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
4623         assert_eq!(c_txn.len(), 3);
4624         assert_eq!(c_txn[0], c_txn[2]);
4625         assert_eq!(commitment_tx[0], c_txn[1]);
4626         check_spends!(c_txn[1], chan_2.3);
4627         check_spends!(c_txn[2], c_txn[1]);
4628         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
4629         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4630         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4631         assert_eq!(c_txn[0].lock_time, 0); // Success tx
4632
4633         // 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
4634         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
4635         {
4636                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4637                 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-timeout tx
4638                 assert_eq!(b_txn.len(), 3);
4639                 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
4640                 check_spends!(b_txn[2], b_txn[1]); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
4641                 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4642                 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4643                 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
4644                 check_spends!(b_txn[0], c_txn[1]); // timeout tx on C remote commitment tx, issued by ChannelMonitor, * 2 due to block rescan
4645                 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4646                 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4647                 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
4648                 b_txn.clear();
4649         }
4650         check_added_monitors!(nodes[1], 1);
4651         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4652         check_added_monitors!(nodes[1], 1);
4653         match msg_events[0] {
4654                 MessageSendEvent::BroadcastChannelUpdate {  .. } => {},
4655                 _ => panic!("Unexpected event"),
4656         }
4657         match msg_events[1] {
4658                 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, .. } } => {
4659                         assert!(update_add_htlcs.is_empty());
4660                         assert!(update_fail_htlcs.is_empty());
4661                         assert_eq!(update_fulfill_htlcs.len(), 1);
4662                         assert!(update_fail_malformed_htlcs.is_empty());
4663                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4664                 },
4665                 _ => panic!("Unexpected event"),
4666         };
4667         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4668         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4669         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
4670         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4671         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
4672         assert_eq!(b_txn.len(), 3);
4673         check_spends!(b_txn[1], chan_1.3);
4674         check_spends!(b_txn[2], b_txn[1]);
4675         check_spends!(b_txn[0], commitment_tx[0]);
4676         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4677         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4678         assert_eq!(b_txn[0].lock_time, 0); // Success tx
4679
4680         check_closed_broadcast!(nodes[1], false);
4681         check_added_monitors!(nodes[1], 1);
4682 }
4683
4684 #[test]
4685 fn test_duplicate_payment_hash_one_failure_one_success() {
4686         // Topology : A --> B --> C
4687         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4688         let chanmon_cfgs = create_chanmon_cfgs(3);
4689         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4690         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4691         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4692
4693         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4694         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4695
4696         let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
4697         *nodes[0].network_payment_count.borrow_mut() -= 1;
4698         assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
4699
4700         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4701         assert_eq!(commitment_txn[0].input.len(), 1);
4702         check_spends!(commitment_txn[0], chan_2.3);
4703
4704         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4705         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
4706         check_closed_broadcast!(nodes[1], false);
4707         check_added_monitors!(nodes[1], 1);
4708
4709         let htlc_timeout_tx;
4710         { // Extract one of the two HTLC-Timeout transaction
4711                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4712                 // ChannelMonitor: timeout tx * 2, ChannelManager: local commitment tx + HTLC-timeout * 2
4713                 assert_eq!(node_txn.len(), 5);
4714                 check_spends!(node_txn[0], commitment_txn[0]);
4715                 assert_eq!(node_txn[0].input.len(), 1);
4716                 check_spends!(node_txn[1], commitment_txn[0]);
4717                 assert_eq!(node_txn[1].input.len(), 1);
4718                 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
4719                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4720                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4721                 check_spends!(node_txn[2], chan_2.3);
4722                 check_spends!(node_txn[3], node_txn[2]);
4723                 check_spends!(node_txn[4], node_txn[2]);
4724                 htlc_timeout_tx = node_txn[1].clone();
4725         }
4726
4727         nodes[2].node.claim_funds(our_payment_preimage, &None, 900_000);
4728         nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
4729         check_added_monitors!(nodes[2], 3);
4730         let events = nodes[2].node.get_and_clear_pending_msg_events();
4731         match events[0] {
4732                 MessageSendEvent::UpdateHTLCs { .. } => {},
4733                 _ => panic!("Unexpected event"),
4734         }
4735         match events[1] {
4736                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4737                 _ => panic!("Unexepected event"),
4738         }
4739         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4740         assert_eq!(htlc_success_txn.len(), 5); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs), ChannelManager: local commitment tx + HTLC-Success txn (*2 due to 2-HTLC outputs)
4741         check_spends!(htlc_success_txn[2], chan_2.3);
4742         check_spends!(htlc_success_txn[3], htlc_success_txn[2]);
4743         check_spends!(htlc_success_txn[4], htlc_success_txn[2]);
4744         assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
4745         assert_eq!(htlc_success_txn[0].input.len(), 1);
4746         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4747         assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
4748         assert_eq!(htlc_success_txn[1].input.len(), 1);
4749         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4750         assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
4751         check_spends!(htlc_success_txn[0], commitment_txn[0]);
4752         check_spends!(htlc_success_txn[1], commitment_txn[0]);
4753
4754         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![htlc_timeout_tx] }, 200);
4755         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 200, true, header.bitcoin_hash());
4756         expect_pending_htlcs_forwardable!(nodes[1]);
4757         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4758         assert!(htlc_updates.update_add_htlcs.is_empty());
4759         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4760         assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
4761         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4762         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4763         check_added_monitors!(nodes[1], 1);
4764
4765         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4766         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4767         {
4768                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4769                 let events = nodes[0].node.get_and_clear_pending_msg_events();
4770                 assert_eq!(events.len(), 1);
4771                 match events[0] {
4772                         MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. }  } => {
4773                         },
4774                         _ => { panic!("Unexpected event"); }
4775                 }
4776         }
4777         expect_payment_failed!(nodes[0], duplicate_payment_hash, false);
4778
4779         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4780         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
4781         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4782         assert!(updates.update_add_htlcs.is_empty());
4783         assert!(updates.update_fail_htlcs.is_empty());
4784         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4785         assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
4786         assert!(updates.update_fail_malformed_htlcs.is_empty());
4787         check_added_monitors!(nodes[1], 1);
4788
4789         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4790         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4791
4792         let events = nodes[0].node.get_and_clear_pending_events();
4793         match events[0] {
4794                 Event::PaymentSent { ref payment_preimage } => {
4795                         assert_eq!(*payment_preimage, our_payment_preimage);
4796                 }
4797                 _ => panic!("Unexpected event"),
4798         }
4799 }
4800
4801 #[test]
4802 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4803         let chanmon_cfgs = create_chanmon_cfgs(2);
4804         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4805         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4806         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4807
4808         // Create some initial channels
4809         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4810
4811         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
4812         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4813         assert_eq!(local_txn[0].input.len(), 1);
4814         check_spends!(local_txn[0], chan_1.3);
4815
4816         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4817         nodes[1].node.claim_funds(payment_preimage, &None, 9_000_000);
4818         check_added_monitors!(nodes[1], 1);
4819         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4820         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![local_txn[0].clone()] }, 1);
4821         check_added_monitors!(nodes[1], 1);
4822         let events = nodes[1].node.get_and_clear_pending_msg_events();
4823         match events[0] {
4824                 MessageSendEvent::UpdateHTLCs { .. } => {},
4825                 _ => panic!("Unexpected event"),
4826         }
4827         match events[1] {
4828                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4829                 _ => panic!("Unexepected event"),
4830         }
4831         let node_txn = {
4832                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4833                 assert_eq!(node_txn[0].input.len(), 1);
4834                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4835                 check_spends!(node_txn[0], local_txn[0]);
4836                 vec![node_txn[0].clone(), node_txn[2].clone()]
4837         };
4838
4839         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4840         nodes[1].block_notifier.block_connected(&Block { header: header_201, txdata: node_txn.clone() }, 201);
4841         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 201, true, header_201.bitcoin_hash());
4842
4843         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4844         let spend_txn = check_spendable_outputs!(nodes[1], 1);
4845         assert_eq!(spend_txn.len(), 2);
4846         check_spends!(spend_txn[0], node_txn[0]);
4847         check_spends!(spend_txn[1], node_txn[1]);
4848 }
4849
4850 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4851         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4852         // unrevoked commitment transaction.
4853         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4854         // a remote RAA before they could be failed backwards (and combinations thereof).
4855         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4856         // use the same payment hashes.
4857         // Thus, we use a six-node network:
4858         //
4859         // A \         / E
4860         //    - C - D -
4861         // B /         \ F
4862         // And test where C fails back to A/B when D announces its latest commitment transaction
4863         let chanmon_cfgs = create_chanmon_cfgs(6);
4864         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
4865         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
4866         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
4867         let logger = Arc::new(test_utils::TestLogger::new());
4868
4869         create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
4870         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4871         let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
4872         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
4873         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
4874
4875         // Rebalance and check output sanity...
4876         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000, 500_000);
4877         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000, 500_000);
4878         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
4879
4880         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
4881         // 0th HTLC:
4882         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
4883         // 1st HTLC:
4884         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
4885         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4886         let our_node_id = &nodes[1].node.get_our_node_id();
4887         let route = get_route(our_node_id, net_graph_msg_handler, &nodes[5].node.get_our_node_id(), None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV, logger.clone()).unwrap();
4888         // 2nd HTLC:
4889         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
4890         // 3rd HTLC:
4891         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
4892         // 4th HTLC:
4893         let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4894         // 5th HTLC:
4895         let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4896         let route = get_route(our_node_id, net_graph_msg_handler, &nodes[5].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, logger.clone()).unwrap();
4897         // 6th HTLC:
4898         send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
4899         // 7th HTLC:
4900         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
4901
4902         // 8th HTLC:
4903         let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4904         // 9th HTLC:
4905         let route = get_route(our_node_id, net_graph_msg_handler, &nodes[5].node.get_our_node_id(), None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV, logger.clone()).unwrap();
4906         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
4907
4908         // 10th HTLC:
4909         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
4910         // 11th HTLC:
4911         let route = get_route(our_node_id, net_graph_msg_handler, &nodes[5].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, logger.clone()).unwrap();
4912         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
4913
4914         // Double-check that six of the new HTLC were added
4915         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
4916         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
4917         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
4918         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
4919
4920         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
4921         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
4922         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1, &None));
4923         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3, &None));
4924         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5, &None));
4925         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6, &None));
4926         check_added_monitors!(nodes[4], 0);
4927         expect_pending_htlcs_forwardable!(nodes[4]);
4928         check_added_monitors!(nodes[4], 1);
4929
4930         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
4931         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
4932         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
4933         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
4934         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
4935         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
4936
4937         // Fail 3rd below-dust and 7th above-dust HTLCs
4938         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2, &None));
4939         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4, &None));
4940         check_added_monitors!(nodes[5], 0);
4941         expect_pending_htlcs_forwardable!(nodes[5]);
4942         check_added_monitors!(nodes[5], 1);
4943
4944         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
4945         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
4946         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
4947         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
4948
4949         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
4950
4951         expect_pending_htlcs_forwardable!(nodes[3]);
4952         check_added_monitors!(nodes[3], 1);
4953         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
4954         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
4955         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
4956         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
4957         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
4958         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
4959         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
4960         if deliver_last_raa {
4961                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
4962         } else {
4963                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
4964         }
4965
4966         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
4967         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
4968         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
4969         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
4970         //
4971         // We now broadcast the latest commitment transaction, which *should* result in failures for
4972         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
4973         // the non-broadcast above-dust HTLCs.
4974         //
4975         // Alternatively, we may broadcast the previous commitment transaction, which should only
4976         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
4977         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
4978
4979         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4980         if announce_latest {
4981                 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![ds_last_commitment_tx[0].clone()]}, 1);
4982         } else {
4983                 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![ds_prev_commitment_tx[0].clone()]}, 1);
4984         }
4985         connect_blocks(&nodes[2].block_notifier, ANTI_REORG_DELAY - 1, 1, true,  header.bitcoin_hash());
4986         check_closed_broadcast!(nodes[2], false);
4987         expect_pending_htlcs_forwardable!(nodes[2]);
4988         check_added_monitors!(nodes[2], 3);
4989
4990         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
4991         assert_eq!(cs_msgs.len(), 2);
4992         let mut a_done = false;
4993         for msg in cs_msgs {
4994                 match msg {
4995                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
4996                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
4997                                 // should be failed-backwards here.
4998                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
4999                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5000                                         for htlc in &updates.update_fail_htlcs {
5001                                                 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 });
5002                                         }
5003                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5004                                         assert!(!a_done);
5005                                         a_done = true;
5006                                         &nodes[0]
5007                                 } else {
5008                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5009                                         for htlc in &updates.update_fail_htlcs {
5010                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5011                                         }
5012                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5013                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5014                                         &nodes[1]
5015                                 };
5016                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5017                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5018                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5019                                 if announce_latest {
5020                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5021                                         if *node_id == nodes[0].node.get_our_node_id() {
5022                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5023                                         }
5024                                 }
5025                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5026                         },
5027                         _ => panic!("Unexpected event"),
5028                 }
5029         }
5030
5031         let as_events = nodes[0].node.get_and_clear_pending_events();
5032         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5033         let mut as_failds = HashSet::new();
5034         for event in as_events.iter() {
5035                 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5036                         assert!(as_failds.insert(*payment_hash));
5037                         if *payment_hash != payment_hash_2 {
5038                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5039                         } else {
5040                                 assert!(!rejected_by_dest);
5041                         }
5042                 } else { panic!("Unexpected event"); }
5043         }
5044         assert!(as_failds.contains(&payment_hash_1));
5045         assert!(as_failds.contains(&payment_hash_2));
5046         if announce_latest {
5047                 assert!(as_failds.contains(&payment_hash_3));
5048                 assert!(as_failds.contains(&payment_hash_5));
5049         }
5050         assert!(as_failds.contains(&payment_hash_6));
5051
5052         let bs_events = nodes[1].node.get_and_clear_pending_events();
5053         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5054         let mut bs_failds = HashSet::new();
5055         for event in bs_events.iter() {
5056                 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5057                         assert!(bs_failds.insert(*payment_hash));
5058                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5059                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5060                         } else {
5061                                 assert!(!rejected_by_dest);
5062                         }
5063                 } else { panic!("Unexpected event"); }
5064         }
5065         assert!(bs_failds.contains(&payment_hash_1));
5066         assert!(bs_failds.contains(&payment_hash_2));
5067         if announce_latest {
5068                 assert!(bs_failds.contains(&payment_hash_4));
5069         }
5070         assert!(bs_failds.contains(&payment_hash_5));
5071
5072         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5073         // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
5074         // to unknown-preimage-etc, B should have gotten 2. Thus, in the
5075         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
5076         // PaymentFailureNetworkUpdates.
5077         let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
5078         assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5079         let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5080         assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5081         for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
5082                 match event {
5083                         &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
5084                         _ => panic!("Unexpected event"),
5085                 }
5086         }
5087 }
5088
5089 #[test]
5090 fn test_fail_backwards_latest_remote_announce_a() {
5091         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5092 }
5093
5094 #[test]
5095 fn test_fail_backwards_latest_remote_announce_b() {
5096         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5097 }
5098
5099 #[test]
5100 fn test_fail_backwards_previous_remote_announce() {
5101         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5102         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5103         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5104 }
5105
5106 #[test]
5107 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5108         let chanmon_cfgs = create_chanmon_cfgs(2);
5109         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5110         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5111         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5112
5113         // Create some initial channels
5114         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5115
5116         let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5117         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5118         assert_eq!(local_txn[0].input.len(), 1);
5119         check_spends!(local_txn[0], chan_1.3);
5120
5121         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5122         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5123         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![local_txn[0].clone()] }, 200);
5124         check_closed_broadcast!(nodes[0], false);
5125         check_added_monitors!(nodes[0], 1);
5126
5127         let htlc_timeout = {
5128                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5129                 assert_eq!(node_txn[0].input.len(), 1);
5130                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5131                 check_spends!(node_txn[0], local_txn[0]);
5132                 node_txn[0].clone()
5133         };
5134
5135         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5136         nodes[0].block_notifier.block_connected(&Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
5137         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 201, true, header_201.bitcoin_hash());
5138         expect_payment_failed!(nodes[0], our_payment_hash, true);
5139
5140         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5141         let spend_txn = check_spendable_outputs!(nodes[0], 1);
5142         assert_eq!(spend_txn.len(), 3);
5143         assert_eq!(spend_txn[0], spend_txn[1]);
5144         check_spends!(spend_txn[0], local_txn[0]);
5145         check_spends!(spend_txn[2], htlc_timeout);
5146 }
5147
5148 #[test]
5149 fn test_static_output_closing_tx() {
5150         let chanmon_cfgs = create_chanmon_cfgs(2);
5151         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5152         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5153         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5154
5155         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5156
5157         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
5158         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5159
5160         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5161         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![closing_tx.clone()] }, 0);
5162         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 0, true, header.bitcoin_hash());
5163
5164         let spend_txn = check_spendable_outputs!(nodes[0], 2);
5165         assert_eq!(spend_txn.len(), 1);
5166         check_spends!(spend_txn[0], closing_tx);
5167
5168         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![closing_tx.clone()] }, 0);
5169         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 0, true, header.bitcoin_hash());
5170
5171         let spend_txn = check_spendable_outputs!(nodes[1], 2);
5172         assert_eq!(spend_txn.len(), 1);
5173         check_spends!(spend_txn[0], closing_tx);
5174 }
5175
5176 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5177         let chanmon_cfgs = create_chanmon_cfgs(2);
5178         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5179         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5180         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5181         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5182
5183         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5184
5185         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5186         // present in B's local commitment transaction, but none of A's commitment transactions.
5187         assert!(nodes[1].node.claim_funds(our_payment_preimage, &None, if use_dust { 50_000 } else { 3_000_000 }));
5188         check_added_monitors!(nodes[1], 1);
5189
5190         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5191         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5192         let events = nodes[0].node.get_and_clear_pending_events();
5193         assert_eq!(events.len(), 1);
5194         match events[0] {
5195                 Event::PaymentSent { payment_preimage } => {
5196                         assert_eq!(payment_preimage, our_payment_preimage);
5197                 },
5198                 _ => panic!("Unexpected event"),
5199         }
5200
5201         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5202         check_added_monitors!(nodes[0], 1);
5203         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5204         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5205         check_added_monitors!(nodes[1], 1);
5206
5207         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5208         for i in 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + CHAN_CONFIRM_DEPTH + 1 {
5209                 nodes[1].block_notifier.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
5210                 header.prev_blockhash = header.bitcoin_hash();
5211         }
5212         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5213         check_closed_broadcast!(nodes[1], false);
5214         check_added_monitors!(nodes[1], 1);
5215 }
5216
5217 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5218         let chanmon_cfgs = create_chanmon_cfgs(2);
5219         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5220         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5221         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5222         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5223         let logger = Arc::new(test_utils::TestLogger::new());
5224
5225         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5226         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5227         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &Vec::new(), if use_dust { 50000 } else { 3000000 }, TEST_FINAL_CLTV, logger.clone()).unwrap();
5228         nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
5229         check_added_monitors!(nodes[0], 1);
5230
5231         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5232
5233         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5234         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5235         // to "time out" the HTLC.
5236
5237         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5238
5239         for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5240                 nodes[0].block_notifier.block_connected(&Block { header, txdata: Vec::new()}, i);
5241                 header.prev_blockhash = header.bitcoin_hash();
5242         }
5243         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5244         check_closed_broadcast!(nodes[0], false);
5245         check_added_monitors!(nodes[0], 1);
5246 }
5247
5248 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5249         let chanmon_cfgs = create_chanmon_cfgs(3);
5250         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5251         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5252         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5253         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5254
5255         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5256         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5257         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5258         // actually revoked.
5259         let htlc_value = if use_dust { 50000 } else { 3000000 };
5260         let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5261         assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash, &None));
5262         expect_pending_htlcs_forwardable!(nodes[1]);
5263         check_added_monitors!(nodes[1], 1);
5264
5265         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5266         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5267         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5268         check_added_monitors!(nodes[0], 1);
5269         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5270         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5271         check_added_monitors!(nodes[1], 1);
5272         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5273         check_added_monitors!(nodes[1], 1);
5274         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5275
5276         if check_revoke_no_close {
5277                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5278                 check_added_monitors!(nodes[0], 1);
5279         }
5280
5281         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5282         for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5283                 nodes[0].block_notifier.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
5284                 header.prev_blockhash = header.bitcoin_hash();
5285         }
5286         if !check_revoke_no_close {
5287                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5288                 check_closed_broadcast!(nodes[0], false);
5289                 check_added_monitors!(nodes[0], 1);
5290         } else {
5291                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5292         }
5293 }
5294
5295 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5296 // There are only a few cases to test here:
5297 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5298 //    broadcastable commitment transactions result in channel closure,
5299 //  * its included in an unrevoked-but-previous remote commitment transaction,
5300 //  * its included in the latest remote or local commitment transactions.
5301 // We test each of the three possible commitment transactions individually and use both dust and
5302 // non-dust HTLCs.
5303 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5304 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5305 // tested for at least one of the cases in other tests.
5306 #[test]
5307 fn htlc_claim_single_commitment_only_a() {
5308         do_htlc_claim_local_commitment_only(true);
5309         do_htlc_claim_local_commitment_only(false);
5310
5311         do_htlc_claim_current_remote_commitment_only(true);
5312         do_htlc_claim_current_remote_commitment_only(false);
5313 }
5314
5315 #[test]
5316 fn htlc_claim_single_commitment_only_b() {
5317         do_htlc_claim_previous_remote_commitment_only(true, false);
5318         do_htlc_claim_previous_remote_commitment_only(false, false);
5319         do_htlc_claim_previous_remote_commitment_only(true, true);
5320         do_htlc_claim_previous_remote_commitment_only(false, true);
5321 }
5322
5323 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>)
5324         where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
5325                                 F2: FnMut(),
5326 {
5327         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);
5328 }
5329
5330 // test_case
5331 // 0: node1 fails backward
5332 // 1: final node fails backward
5333 // 2: payment completed but the user rejects the payment
5334 // 3: final node fails backward (but tamper onion payloads from node0)
5335 // 100: trigger error in the intermediate node and tamper returning fail_htlc
5336 // 200: trigger error in the final node and tamper returning fail_htlc
5337 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>)
5338         where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
5339                                 F2: for <'a> FnMut(&'a mut msgs::UpdateFailHTLC),
5340                                 F3: FnMut(),
5341 {
5342
5343         // reset block height
5344         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5345         for ix in 0..nodes.len() {
5346                 nodes[ix].block_notifier.block_connected_checked(&header, 1, &[], &[]);
5347         }
5348
5349         macro_rules! expect_event {
5350                 ($node: expr, $event_type: path) => {{
5351                         let events = $node.node.get_and_clear_pending_events();
5352                         assert_eq!(events.len(), 1);
5353                         match events[0] {
5354                                 $event_type { .. } => {},
5355                                 _ => panic!("Unexpected event"),
5356                         }
5357                 }}
5358         }
5359
5360         macro_rules! expect_htlc_forward {
5361                 ($node: expr) => {{
5362                         expect_event!($node, Event::PendingHTLCsForwardable);
5363                         $node.node.process_pending_htlc_forwards();
5364                 }}
5365         }
5366
5367         // 0 ~~> 2 send payment
5368         nodes[0].node.send_payment(&route, payment_hash.clone(), &None).unwrap();
5369         check_added_monitors!(nodes[0], 1);
5370         let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5371         // temper update_add (0 => 1)
5372         let mut update_add_0 = update_0.update_add_htlcs[0].clone();
5373         if test_case == 0 || test_case == 3 || test_case == 100 {
5374                 callback_msg(&mut update_add_0);
5375                 callback_node();
5376         }
5377         // 0 => 1 update_add & CS
5378         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_0);
5379         commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
5380
5381         let update_1_0 = match test_case {
5382                 0|100 => { // intermediate node failure; fail backward to 0
5383                         let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5384                         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));
5385                         update_1_0
5386                 },
5387                 1|2|3|200 => { // final node failure; forwarding to 2
5388                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5389                         // forwarding on 1
5390                         if test_case != 200 {
5391                                 callback_node();
5392                         }
5393                         expect_htlc_forward!(&nodes[1]);
5394
5395                         let update_1 = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
5396                         check_added_monitors!(&nodes[1], 1);
5397                         assert_eq!(update_1.update_add_htlcs.len(), 1);
5398                         // tamper update_add (1 => 2)
5399                         let mut update_add_1 = update_1.update_add_htlcs[0].clone();
5400                         if test_case != 3 && test_case != 200 {
5401                                 callback_msg(&mut update_add_1);
5402                         }
5403
5404                         // 1 => 2
5405                         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_1);
5406                         commitment_signed_dance!(nodes[2], nodes[1], update_1.commitment_signed, false, true);
5407
5408                         if test_case == 2 || test_case == 200 {
5409                                 expect_htlc_forward!(&nodes[2]);
5410                                 expect_event!(&nodes[2], Event::PaymentReceived);
5411                                 callback_node();
5412                                 expect_pending_htlcs_forwardable!(nodes[2]);
5413                         }
5414
5415                         let update_2_1 = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5416                         if test_case == 2 || test_case == 200 {
5417                                 check_added_monitors!(&nodes[2], 1);
5418                         }
5419                         assert!(update_2_1.update_fail_htlcs.len() == 1);
5420
5421                         let mut fail_msg = update_2_1.update_fail_htlcs[0].clone();
5422                         if test_case == 200 {
5423                                 callback_fail(&mut fail_msg);
5424                         }
5425
5426                         // 2 => 1
5427                         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_msg);
5428                         commitment_signed_dance!(nodes[1], nodes[2], update_2_1.commitment_signed, true);
5429
5430                         // backward fail on 1
5431                         let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5432                         assert!(update_1_0.update_fail_htlcs.len() == 1);
5433                         update_1_0
5434                 },
5435                 _ => unreachable!(),
5436         };
5437
5438         // 1 => 0 commitment_signed_dance
5439         if update_1_0.update_fail_htlcs.len() > 0 {
5440                 let mut fail_msg = update_1_0.update_fail_htlcs[0].clone();
5441                 if test_case == 100 {
5442                         callback_fail(&mut fail_msg);
5443                 }
5444                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
5445         } else {
5446                 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_1_0.update_fail_malformed_htlcs[0]);
5447         };
5448
5449         commitment_signed_dance!(nodes[0], nodes[1], update_1_0.commitment_signed, false, true);
5450
5451         let events = nodes[0].node.get_and_clear_pending_events();
5452         assert_eq!(events.len(), 1);
5453         if let &Event::PaymentFailed { payment_hash:_, ref rejected_by_dest, ref error_code, error_data: _ } = &events[0] {
5454                 assert_eq!(*rejected_by_dest, !expected_retryable);
5455                 assert_eq!(*error_code, expected_error_code);
5456         } else {
5457                 panic!("Uexpected event");
5458         }
5459
5460         let events = nodes[0].node.get_and_clear_pending_msg_events();
5461         if expected_channel_update.is_some() {
5462                 assert_eq!(events.len(), 1);
5463                 match events[0] {
5464                         MessageSendEvent::PaymentFailureNetworkUpdate { ref update } => {
5465                                 match update {
5466                                         &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {
5467                                                 if let HTLCFailChannelUpdate::ChannelUpdateMessage { .. } = expected_channel_update.unwrap() {} else {
5468                                                         panic!("channel_update not found!");
5469                                                 }
5470                                         },
5471                                         &HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, ref is_permanent } => {
5472                                                 if let HTLCFailChannelUpdate::ChannelClosed { short_channel_id: ref expected_short_channel_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
5473                                                         assert!(*short_channel_id == *expected_short_channel_id);
5474                                                         assert!(*is_permanent == *expected_is_permanent);
5475                                                 } else {
5476                                                         panic!("Unexpected message event");
5477                                                 }
5478                                         },
5479                                         &HTLCFailChannelUpdate::NodeFailure { ref node_id, ref is_permanent } => {
5480                                                 if let HTLCFailChannelUpdate::NodeFailure { node_id: ref expected_node_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
5481                                                         assert!(*node_id == *expected_node_id);
5482                                                         assert!(*is_permanent == *expected_is_permanent);
5483                                                 } else {
5484                                                         panic!("Unexpected message event");
5485                                                 }
5486                                         },
5487                                 }
5488                         },
5489                         _ => panic!("Unexpected message event"),
5490                 }
5491         } else {
5492                 assert_eq!(events.len(), 0);
5493         }
5494 }
5495
5496 impl msgs::ChannelUpdate {
5497         fn dummy() -> msgs::ChannelUpdate {
5498                 use bitcoin::secp256k1::ffi::Signature as FFISignature;
5499                 use bitcoin::secp256k1::Signature;
5500                 msgs::ChannelUpdate {
5501                         signature: Signature::from(FFISignature::new()),
5502                         contents: msgs::UnsignedChannelUpdate {
5503                                 chain_hash: BlockHash::hash(&vec![0u8][..]),
5504                                 short_channel_id: 0,
5505                                 timestamp: 0,
5506                                 flags: 0,
5507                                 cltv_expiry_delta: 0,
5508                                 htlc_minimum_msat: 0,
5509                                 fee_base_msat: 0,
5510                                 fee_proportional_millionths: 0,
5511                                 excess_data: vec![],
5512                         }
5513                 }
5514         }
5515 }
5516
5517 struct BogusOnionHopData {
5518         data: Vec<u8>
5519 }
5520 impl BogusOnionHopData {
5521         fn new(orig: msgs::OnionHopData) -> Self {
5522                 Self { data: orig.encode() }
5523         }
5524 }
5525 impl Writeable for BogusOnionHopData {
5526         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
5527                 writer.write_all(&self.data[..])
5528         }
5529 }
5530
5531 #[test]
5532 fn test_onion_failure() {
5533         use ln::msgs::ChannelUpdate;
5534         use ln::channelmanager::CLTV_FAR_FAR_AWAY;
5535         use bitcoin::secp256k1;
5536
5537         const BADONION: u16 = 0x8000;
5538         const PERM: u16 = 0x4000;
5539         const NODE: u16 = 0x2000;
5540         const UPDATE: u16 = 0x1000;
5541
5542         let chanmon_cfgs = create_chanmon_cfgs(3);
5543         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5544         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5545         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5546         for node in nodes.iter() {
5547                 *node.keys_manager.override_session_priv.lock().unwrap() = Some(SecretKey::from_slice(&[3; 32]).unwrap());
5548         }
5549         let channels = [create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()), create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known())];
5550         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5551         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5552         let logger = Arc::new(test_utils::TestLogger::new());
5553         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV, logger.clone()).unwrap();
5554         // positve case
5555         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 40000, 40_000);
5556
5557         // intermediate node failure
5558         run_onion_failure_test("invalid_realm", 0, &nodes, &route, &payment_hash, |msg| {
5559                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5560                 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5561                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5562                 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 40000, &None, cur_height).unwrap();
5563                 let mut new_payloads = Vec::new();
5564                 for payload in onion_payloads.drain(..) {
5565                         new_payloads.push(BogusOnionHopData::new(payload));
5566                 }
5567                 // break the first (non-final) hop payload by swapping the realm (0) byte for a byte
5568                 // describing a length-1 TLV payload, which is obviously bogus.
5569                 new_payloads[0].data[0] = 1;
5570                 msg.onion_routing_packet = onion_utils::construct_onion_packet_bogus_hopdata(new_payloads, onion_keys, [0; 32], &payment_hash);
5571         }, ||{}, true, Some(PERM|22), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));//XXX incremented channels idx here
5572
5573         // final node failure
5574         run_onion_failure_test("invalid_realm", 3, &nodes, &route, &payment_hash, |msg| {
5575                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5576                 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5577                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5578                 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 40000, &None, cur_height).unwrap();
5579                 let mut new_payloads = Vec::new();
5580                 for payload in onion_payloads.drain(..) {
5581                         new_payloads.push(BogusOnionHopData::new(payload));
5582                 }
5583                 // break the last-hop payload by swapping the realm (0) byte for a byte describing a
5584                 // length-1 TLV payload, which is obviously bogus.
5585                 new_payloads[1].data[0] = 1;
5586                 msg.onion_routing_packet = onion_utils::construct_onion_packet_bogus_hopdata(new_payloads, onion_keys, [0; 32], &payment_hash);
5587         }, ||{}, false, Some(PERM|22), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
5588
5589         // the following three with run_onion_failure_test_with_fail_intercept() test only the origin node
5590         // receiving simulated fail messages
5591         // intermediate node failure
5592         run_onion_failure_test_with_fail_intercept("temporary_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
5593                 // trigger error
5594                 msg.amount_msat -= 1;
5595         }, |msg| {
5596                 // and tamper returning error message
5597                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5598                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5599                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], NODE|2, &[0;0]);
5600         }, ||{}, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][0].pubkey, is_permanent: false}));
5601
5602         // final node failure
5603         run_onion_failure_test_with_fail_intercept("temporary_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
5604                 // and tamper returning error message
5605                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5606                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5607                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], NODE|2, &[0;0]);
5608         }, ||{
5609                 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
5610         }, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][1].pubkey, is_permanent: false}));
5611
5612         // intermediate node failure
5613         run_onion_failure_test_with_fail_intercept("permanent_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
5614                 msg.amount_msat -= 1;
5615         }, |msg| {
5616                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5617                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5618                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|2, &[0;0]);
5619         }, ||{}, true, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][0].pubkey, is_permanent: true}));
5620
5621         // final node failure
5622         run_onion_failure_test_with_fail_intercept("permanent_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
5623                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5624                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5625                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|2, &[0;0]);
5626         }, ||{
5627                 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
5628         }, false, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][1].pubkey, is_permanent: true}));
5629
5630         // intermediate node failure
5631         run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
5632                 msg.amount_msat -= 1;
5633         }, |msg| {
5634                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5635                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5636                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|3, &[0;0]);
5637         }, ||{
5638                 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
5639         }, true, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][0].pubkey, is_permanent: true}));
5640
5641         // final node failure
5642         run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
5643                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5644                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5645                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|3, &[0;0]);
5646         }, ||{
5647                 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
5648         }, false, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][1].pubkey, is_permanent: true}));
5649
5650         run_onion_failure_test("invalid_onion_version", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.version = 1; }, ||{}, true,
5651                 Some(BADONION|PERM|4), None);
5652
5653         run_onion_failure_test("invalid_onion_hmac", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.hmac = [3; 32]; }, ||{}, true,
5654                 Some(BADONION|PERM|5), None);
5655
5656         run_onion_failure_test("invalid_onion_key", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.public_key = Err(secp256k1::Error::InvalidPublicKey);}, ||{}, true,
5657                 Some(BADONION|PERM|6), None);
5658
5659         run_onion_failure_test_with_fail_intercept("temporary_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
5660                 msg.amount_msat -= 1;
5661         }, |msg| {
5662                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5663                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5664                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], UPDATE|7, &ChannelUpdate::dummy().encode_with_len()[..]);
5665         }, ||{}, true, Some(UPDATE|7), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5666
5667         run_onion_failure_test_with_fail_intercept("permanent_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
5668                 msg.amount_msat -= 1;
5669         }, |msg| {
5670                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5671                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5672                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|8, &[0;0]);
5673                 // short_channel_id from the processing node
5674         }, ||{}, true, Some(PERM|8), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
5675
5676         run_onion_failure_test_with_fail_intercept("required_channel_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
5677                 msg.amount_msat -= 1;
5678         }, |msg| {
5679                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5680                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5681                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|9, &[0;0]);
5682                 // short_channel_id from the processing node
5683         }, ||{}, true, Some(PERM|9), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
5684
5685         let mut bogus_route = route.clone();
5686         bogus_route.paths[0][1].short_channel_id -= 1;
5687         run_onion_failure_test("unknown_next_peer", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(PERM|10),
5688           Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: bogus_route.paths[0][1].short_channel_id, is_permanent:true}));
5689
5690         let amt_to_forward = nodes[1].node.channel_state.lock().unwrap().by_id.get(&channels[1].2).unwrap().get_their_htlc_minimum_msat() - 1;
5691         let mut bogus_route = route.clone();
5692         let route_len = bogus_route.paths[0].len();
5693         bogus_route.paths[0][route_len-1].fee_msat = amt_to_forward;
5694         run_onion_failure_test("amount_below_minimum", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(UPDATE|11), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5695
5696         //TODO: with new config API, we will be able to generate both valid and
5697         //invalid channel_update cases.
5698         run_onion_failure_test("fee_insufficient", 0, &nodes, &route, &payment_hash, |msg| {
5699                 msg.amount_msat -= 1;
5700         }, || {}, true, Some(UPDATE|12), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
5701
5702         run_onion_failure_test("incorrect_cltv_expiry", 0, &nodes, &route, &payment_hash, |msg| {
5703                 // need to violate: cltv_expiry - cltv_expiry_delta >= outgoing_cltv_value
5704                 msg.cltv_expiry -= 1;
5705         }, || {}, true, Some(UPDATE|13), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
5706
5707         run_onion_failure_test("expiry_too_soon", 0, &nodes, &route, &payment_hash, |msg| {
5708                 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
5709                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5710
5711                 nodes[1].block_notifier.block_connected_checked(&header, height, &[], &[]);
5712         }, ||{}, true, Some(UPDATE|14), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5713
5714         run_onion_failure_test("unknown_payment_hash", 2, &nodes, &route, &payment_hash, |_| {}, || {
5715                 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
5716         }, false, Some(PERM|15), None);
5717
5718         run_onion_failure_test("final_expiry_too_soon", 1, &nodes, &route, &payment_hash, |msg| {
5719                 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
5720                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5721
5722                 nodes[2].block_notifier.block_connected_checked(&header, height, &[], &[]);
5723         }, || {}, true, Some(17), None);
5724
5725         run_onion_failure_test("final_incorrect_cltv_expiry", 1, &nodes, &route, &payment_hash, |_| {}, || {
5726                 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().forward_htlcs.iter_mut() {
5727                         for f in pending_forwards.iter_mut() {
5728                                 match f {
5729                                         &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
5730                                                 forward_info.outgoing_cltv_value += 1,
5731                                         _ => {},
5732                                 }
5733                         }
5734                 }
5735         }, true, Some(18), None);
5736
5737         run_onion_failure_test("final_incorrect_htlc_amount", 1, &nodes, &route, &payment_hash, |_| {}, || {
5738                 // violate amt_to_forward > msg.amount_msat
5739                 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().forward_htlcs.iter_mut() {
5740                         for f in pending_forwards.iter_mut() {
5741                                 match f {
5742                                         &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
5743                                                 forward_info.amt_to_forward -= 1,
5744                                         _ => {},
5745                                 }
5746                         }
5747                 }
5748         }, true, Some(19), None);
5749
5750         run_onion_failure_test("channel_disabled", 0, &nodes, &route, &payment_hash, |_| {}, || {
5751                 // disconnect event to the channel between nodes[1] ~ nodes[2]
5752                 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
5753                 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5754         }, true, Some(UPDATE|20), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5755         reconnect_nodes(&nodes[1], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5756
5757         run_onion_failure_test("expiry_too_far", 0, &nodes, &route, &payment_hash, |msg| {
5758                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5759                 let mut route = route.clone();
5760                 let height = 1;
5761                 route.paths[0][1].cltv_expiry_delta += CLTV_FAR_FAR_AWAY + route.paths[0][0].cltv_expiry_delta + 1;
5762                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5763                 let (onion_payloads, _, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 40000, &None, height).unwrap();
5764                 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
5765                 msg.cltv_expiry = htlc_cltv;
5766                 msg.onion_routing_packet = onion_packet;
5767         }, ||{}, true, Some(21), None);
5768 }
5769
5770 #[test]
5771 #[should_panic]
5772 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5773         let chanmon_cfgs = create_chanmon_cfgs(2);
5774         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5775         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5776         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5777         //Force duplicate channel ids
5778         for node in nodes.iter() {
5779                 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5780         }
5781
5782         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5783         let channel_value_satoshis=10000;
5784         let push_msat=10001;
5785         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5786         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5787         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5788
5789         //Create a second channel with a channel_id collision
5790         assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5791 }
5792
5793 #[test]
5794 fn bolt2_open_channel_sending_node_checks_part2() {
5795         let chanmon_cfgs = create_chanmon_cfgs(2);
5796         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5797         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5798         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5799
5800         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5801         let channel_value_satoshis=2^24;
5802         let push_msat=10001;
5803         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5804
5805         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5806         let channel_value_satoshis=10000;
5807         // Test when push_msat is equal to 1000 * funding_satoshis.
5808         let push_msat=1000*channel_value_satoshis+1;
5809         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5810
5811         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5812         let channel_value_satoshis=10000;
5813         let push_msat=10001;
5814         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_ok()); //Create a valid channel
5815         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5816         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5817
5818         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5819         // 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
5820         assert!(node0_to_1_send_open_channel.channel_flags<=1);
5821
5822         // 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.
5823         assert!(BREAKDOWN_TIMEOUT>0);
5824         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5825
5826         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5827         let chain_hash=genesis_block(Network::Testnet).header.bitcoin_hash();
5828         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5829
5830         // 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.
5831         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5832         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5833         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5834         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5835         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5836 }
5837
5838 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
5839 // 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.
5840 //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.
5841
5842 #[test]
5843 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
5844         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
5845         let chanmon_cfgs = create_chanmon_cfgs(2);
5846         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5847         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5848         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5849         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
5850
5851         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5852         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5853         let logger = Arc::new(test_utils::TestLogger::new());
5854         let mut route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, logger.clone()).unwrap();
5855         route.paths[0][0].fee_msat = 100;
5856
5857         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
5858                 assert_eq!(err, "Cannot send less than their minimum HTLC value"));
5859         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5860         nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
5861 }
5862
5863 #[test]
5864 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
5865         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
5866         let chanmon_cfgs = create_chanmon_cfgs(2);
5867         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5868         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5869         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5870         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
5871         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5872
5873         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5874         let logger = Arc::new(test_utils::TestLogger::new());
5875         let mut route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, logger.clone()).unwrap();
5876         route.paths[0][0].fee_msat = 0;
5877         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
5878                 assert_eq!(err, "Cannot send 0-msat HTLC"));
5879
5880         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5881         nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
5882 }
5883
5884 #[test]
5885 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
5886         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
5887         let chanmon_cfgs = create_chanmon_cfgs(2);
5888         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5889         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5890         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5891         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
5892
5893         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5894         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5895         let logger = Arc::new(test_utils::TestLogger::new());
5896         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, logger.clone()).unwrap();
5897         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
5898         check_added_monitors!(nodes[0], 1);
5899         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5900         updates.update_add_htlcs[0].amount_msat = 0;
5901
5902         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5903         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
5904         check_closed_broadcast!(nodes[1], true).unwrap();
5905         check_added_monitors!(nodes[1], 1);
5906 }
5907
5908 #[test]
5909 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
5910         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
5911         //It is enforced when constructing a route.
5912         let chanmon_cfgs = create_chanmon_cfgs(2);
5913         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5914         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5915         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5916         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 0, InitFeatures::known(), InitFeatures::known());
5917         let logger = Arc::new(test_utils::TestLogger::new());
5918
5919         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5920
5921         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5922         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 100000000, 500000001, logger.clone()).unwrap();
5923         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::RouteError { err },
5924                 assert_eq!(err, "Channel CLTV overflowed?!"));
5925 }
5926
5927 #[test]
5928 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
5929         //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.
5930         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
5931         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
5932         let chanmon_cfgs = create_chanmon_cfgs(2);
5933         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5934         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5935         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5936         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
5937         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().their_max_accepted_htlcs as u64;
5938
5939         let logger = Arc::new(test_utils::TestLogger::new());
5940         for i in 0..max_accepted_htlcs {
5941                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5942                 let payment_event = {
5943                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5944                         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, logger.clone()).unwrap();
5945                         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
5946                         check_added_monitors!(nodes[0], 1);
5947
5948                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5949                         assert_eq!(events.len(), 1);
5950                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
5951                                 assert_eq!(htlcs[0].htlc_id, i);
5952                         } else {
5953                                 assert!(false);
5954                         }
5955                         SendEvent::from_event(events.remove(0))
5956                 };
5957                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5958                 check_added_monitors!(nodes[1], 0);
5959                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5960
5961                 expect_pending_htlcs_forwardable!(nodes[1]);
5962                 expect_payment_received!(nodes[1], our_payment_hash, 100000);
5963         }
5964         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5965         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5966         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, logger.clone()).unwrap();
5967         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
5968                 assert_eq!(err, "Cannot push more than their max accepted HTLCs"));
5969
5970         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5971         nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
5972 }
5973
5974 #[test]
5975 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
5976         //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.
5977         let chanmon_cfgs = create_chanmon_cfgs(2);
5978         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5979         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5980         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5981         let channel_value = 100000;
5982         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
5983         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).their_max_htlc_value_in_flight_msat;
5984
5985         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight, max_in_flight);
5986
5987         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5988         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5989         let logger = Arc::new(test_utils::TestLogger::new());
5990         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], max_in_flight+1, TEST_FINAL_CLTV, logger.clone()).unwrap();
5991         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
5992                 assert_eq!(err, "Cannot send value that would put us over the max HTLC value in flight our peer will accept"));
5993
5994         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5995         nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us over the max HTLC value in flight our peer will accept".to_string(), 1);
5996
5997         send_payment(&nodes[0], &[&nodes[1]], max_in_flight, max_in_flight);
5998 }
5999
6000 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6001 #[test]
6002 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6003         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6004         let chanmon_cfgs = create_chanmon_cfgs(2);
6005         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6006         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6007         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6008         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6009         let htlc_minimum_msat: u64;
6010         {
6011                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6012                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6013                 htlc_minimum_msat = channel.get_our_htlc_minimum_msat();
6014         }
6015
6016         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6017         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6018         let logger = Arc::new(test_utils::TestLogger::new());
6019         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], htlc_minimum_msat, TEST_FINAL_CLTV, logger.clone()).unwrap();
6020         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6021         check_added_monitors!(nodes[0], 1);
6022         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6023         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6024         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6025         assert!(nodes[1].node.list_channels().is_empty());
6026         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6027         assert_eq!(err_msg.data, "Remote side tried to send less than our minimum HTLC value");
6028         check_added_monitors!(nodes[1], 1);
6029 }
6030
6031 #[test]
6032 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6033         //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
6034         let chanmon_cfgs = create_chanmon_cfgs(2);
6035         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6036         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6037         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6038         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6039
6040         let their_channel_reserve = get_channel_value_stat!(nodes[0], chan.2).channel_reserve_msat;
6041
6042         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6043         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6044         let logger = Arc::new(test_utils::TestLogger::new());
6045         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 5000000-their_channel_reserve, TEST_FINAL_CLTV, logger.clone()).unwrap();
6046         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6047         check_added_monitors!(nodes[0], 1);
6048         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6049
6050         updates.update_add_htlcs[0].amount_msat = 5000000-their_channel_reserve+1;
6051         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6052
6053         assert!(nodes[1].node.list_channels().is_empty());
6054         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6055         assert_eq!(err_msg.data, "Remote HTLC add would put them under their reserve value");
6056         check_added_monitors!(nodes[1], 1);
6057 }
6058
6059 #[test]
6060 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6061         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6062         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6063         let chanmon_cfgs = create_chanmon_cfgs(2);
6064         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6065         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6066         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6067         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6068         let logger = Arc::new(test_utils::TestLogger::new());
6069
6070         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6071
6072         let session_priv = SecretKey::from_slice(&{
6073                 let mut session_key = [0; 32];
6074                 let mut rng = thread_rng();
6075                 rng.fill_bytes(&mut session_key);
6076                 session_key
6077         }).expect("RNG is bad!");
6078
6079         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6080         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 3999999, TEST_FINAL_CLTV, logger.clone()).unwrap();
6081
6082         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
6083         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6084         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &None, cur_height).unwrap();
6085         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6086
6087         let mut msg = msgs::UpdateAddHTLC {
6088                 channel_id: chan.2,
6089                 htlc_id: 0,
6090                 amount_msat: 1000,
6091                 payment_hash: our_payment_hash,
6092                 cltv_expiry: htlc_cltv,
6093                 onion_routing_packet: onion_packet.clone(),
6094         };
6095
6096         for i in 0..super::channel::OUR_MAX_HTLCS {
6097                 msg.htlc_id = i as u64;
6098                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6099         }
6100         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6101         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6102
6103         assert!(nodes[1].node.list_channels().is_empty());
6104         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6105         assert_eq!(err_msg.data, "Remote tried to push more than our max accepted HTLCs");
6106         check_added_monitors!(nodes[1], 1);
6107 }
6108
6109 #[test]
6110 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6111         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6112         let chanmon_cfgs = create_chanmon_cfgs(2);
6113         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6114         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6115         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6116         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6117         let logger = Arc::new(test_utils::TestLogger::new());
6118
6119         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6120         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6121         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV, logger.clone()).unwrap();
6122         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6123         check_added_monitors!(nodes[0], 1);
6124         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6125         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).their_max_htlc_value_in_flight_msat + 1;
6126         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6127
6128         assert!(nodes[1].node.list_channels().is_empty());
6129         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6130         assert_eq!(err_msg.data,"Remote HTLC add would put them over our max HTLC value");
6131         check_added_monitors!(nodes[1], 1);
6132 }
6133
6134 #[test]
6135 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6136         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6137         let chanmon_cfgs = create_chanmon_cfgs(2);
6138         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6139         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6140         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6141         let logger = Arc::new(test_utils::TestLogger::new());
6142
6143         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6144         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6145         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6146         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV, logger.clone()).unwrap();
6147         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6148         check_added_monitors!(nodes[0], 1);
6149         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6150         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6151         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6152
6153         assert!(nodes[1].node.list_channels().is_empty());
6154         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6155         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6156         check_added_monitors!(nodes[1], 1);
6157 }
6158
6159 #[test]
6160 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6161         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6162         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6163         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6164         let chanmon_cfgs = create_chanmon_cfgs(2);
6165         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6166         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6167         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6168         let logger = Arc::new(test_utils::TestLogger::new());
6169
6170         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6171         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6172         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6173         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV, logger.clone()).unwrap();
6174         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6175         check_added_monitors!(nodes[0], 1);
6176         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6177         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6178
6179         //Disconnect and Reconnect
6180         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6181         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6182         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6183         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6184         assert_eq!(reestablish_1.len(), 1);
6185         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6186         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6187         assert_eq!(reestablish_2.len(), 1);
6188         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6189         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6190         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6191         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6192
6193         //Resend HTLC
6194         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6195         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6196         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6197         check_added_monitors!(nodes[1], 1);
6198         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6199
6200         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6201
6202         assert!(nodes[1].node.list_channels().is_empty());
6203         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6204         assert_eq!(err_msg.data, "Remote skipped HTLC ID");
6205         check_added_monitors!(nodes[1], 1);
6206 }
6207
6208 #[test]
6209 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6210         //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.
6211
6212         let chanmon_cfgs = create_chanmon_cfgs(2);
6213         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6214         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6215         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6216         let logger = Arc::new(test_utils::TestLogger::new());
6217         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6218         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6219         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6220         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV, logger.clone()).unwrap();
6221         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6222
6223         check_added_monitors!(nodes[0], 1);
6224         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6225         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6226
6227         let update_msg = msgs::UpdateFulfillHTLC{
6228                 channel_id: chan.2,
6229                 htlc_id: 0,
6230                 payment_preimage: our_payment_preimage,
6231         };
6232
6233         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6234
6235         assert!(nodes[0].node.list_channels().is_empty());
6236         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6237         assert_eq!(err_msg.data, "Remote tried to fulfill/fail HTLC before it had been committed");
6238         check_added_monitors!(nodes[0], 1);
6239 }
6240
6241 #[test]
6242 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6243         //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.
6244
6245         let chanmon_cfgs = create_chanmon_cfgs(2);
6246         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6247         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6248         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6249         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6250         let logger = Arc::new(test_utils::TestLogger::new());
6251
6252         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6253         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6254         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV, logger.clone()).unwrap();
6255         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6256         check_added_monitors!(nodes[0], 1);
6257         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6258         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6259
6260         let update_msg = msgs::UpdateFailHTLC{
6261                 channel_id: chan.2,
6262                 htlc_id: 0,
6263                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6264         };
6265
6266         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6267
6268         assert!(nodes[0].node.list_channels().is_empty());
6269         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6270         assert_eq!(err_msg.data, "Remote tried to fulfill/fail HTLC before it had been committed");
6271         check_added_monitors!(nodes[0], 1);
6272 }
6273
6274 #[test]
6275 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6276         //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.
6277
6278         let chanmon_cfgs = create_chanmon_cfgs(2);
6279         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6280         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6281         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6282         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6283         let logger = Arc::new(test_utils::TestLogger::new());
6284
6285         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6286         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6287         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV, logger.clone()).unwrap();
6288         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6289         check_added_monitors!(nodes[0], 1);
6290         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6291         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6292
6293         let update_msg = msgs::UpdateFailMalformedHTLC{
6294                 channel_id: chan.2,
6295                 htlc_id: 0,
6296                 sha256_of_onion: [1; 32],
6297                 failure_code: 0x8000,
6298         };
6299
6300         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6301
6302         assert!(nodes[0].node.list_channels().is_empty());
6303         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6304         assert_eq!(err_msg.data, "Remote tried to fulfill/fail HTLC before it had been committed");
6305         check_added_monitors!(nodes[0], 1);
6306 }
6307
6308 #[test]
6309 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6310         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6311
6312         let chanmon_cfgs = create_chanmon_cfgs(2);
6313         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6314         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6315         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6316         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6317
6318         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6319
6320         nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6321         check_added_monitors!(nodes[1], 1);
6322
6323         let events = nodes[1].node.get_and_clear_pending_msg_events();
6324         assert_eq!(events.len(), 1);
6325         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6326                 match events[0] {
6327                         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, .. } } => {
6328                                 assert!(update_add_htlcs.is_empty());
6329                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6330                                 assert!(update_fail_htlcs.is_empty());
6331                                 assert!(update_fail_malformed_htlcs.is_empty());
6332                                 assert!(update_fee.is_none());
6333                                 update_fulfill_htlcs[0].clone()
6334                         },
6335                         _ => panic!("Unexpected event"),
6336                 }
6337         };
6338
6339         update_fulfill_msg.htlc_id = 1;
6340
6341         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6342
6343         assert!(nodes[0].node.list_channels().is_empty());
6344         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6345         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6346         check_added_monitors!(nodes[0], 1);
6347 }
6348
6349 #[test]
6350 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6351         //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.
6352
6353         let chanmon_cfgs = create_chanmon_cfgs(2);
6354         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6355         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6356         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6357         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6358
6359         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6360
6361         nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6362         check_added_monitors!(nodes[1], 1);
6363
6364         let events = nodes[1].node.get_and_clear_pending_msg_events();
6365         assert_eq!(events.len(), 1);
6366         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6367                 match events[0] {
6368                         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, .. } } => {
6369                                 assert!(update_add_htlcs.is_empty());
6370                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6371                                 assert!(update_fail_htlcs.is_empty());
6372                                 assert!(update_fail_malformed_htlcs.is_empty());
6373                                 assert!(update_fee.is_none());
6374                                 update_fulfill_htlcs[0].clone()
6375                         },
6376                         _ => panic!("Unexpected event"),
6377                 }
6378         };
6379
6380         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6381
6382         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6383
6384         assert!(nodes[0].node.list_channels().is_empty());
6385         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6386         assert_eq!(err_msg.data, "Remote tried to fulfill HTLC with an incorrect preimage");
6387         check_added_monitors!(nodes[0], 1);
6388 }
6389
6390 #[test]
6391 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6392         //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.
6393
6394         let chanmon_cfgs = create_chanmon_cfgs(2);
6395         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6396         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6397         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6398         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6399         let logger = Arc::new(test_utils::TestLogger::new());
6400
6401         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6402         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6403         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV, logger.clone()).unwrap();
6404         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6405         check_added_monitors!(nodes[0], 1);
6406
6407         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6408         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6409
6410         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6411         check_added_monitors!(nodes[1], 0);
6412         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6413
6414         let events = nodes[1].node.get_and_clear_pending_msg_events();
6415
6416         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6417                 match events[0] {
6418                         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, .. } } => {
6419                                 assert!(update_add_htlcs.is_empty());
6420                                 assert!(update_fulfill_htlcs.is_empty());
6421                                 assert!(update_fail_htlcs.is_empty());
6422                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6423                                 assert!(update_fee.is_none());
6424                                 update_fail_malformed_htlcs[0].clone()
6425                         },
6426                         _ => panic!("Unexpected event"),
6427                 }
6428         };
6429         update_msg.failure_code &= !0x8000;
6430         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6431
6432         assert!(nodes[0].node.list_channels().is_empty());
6433         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6434         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6435         check_added_monitors!(nodes[0], 1);
6436 }
6437
6438 #[test]
6439 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6440         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6441         //    * 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.
6442
6443         let chanmon_cfgs = create_chanmon_cfgs(3);
6444         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6445         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6446         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6447         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6448         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6449         let logger = Arc::new(test_utils::TestLogger::new());
6450
6451         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6452
6453         //First hop
6454         let mut payment_event = {
6455                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6456                 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, logger.clone()).unwrap();
6457                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6458                 check_added_monitors!(nodes[0], 1);
6459                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6460                 assert_eq!(events.len(), 1);
6461                 SendEvent::from_event(events.remove(0))
6462         };
6463         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6464         check_added_monitors!(nodes[1], 0);
6465         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6466         expect_pending_htlcs_forwardable!(nodes[1]);
6467         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6468         assert_eq!(events_2.len(), 1);
6469         check_added_monitors!(nodes[1], 1);
6470         payment_event = SendEvent::from_event(events_2.remove(0));
6471         assert_eq!(payment_event.msgs.len(), 1);
6472
6473         //Second Hop
6474         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6475         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6476         check_added_monitors!(nodes[2], 0);
6477         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6478
6479         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6480         assert_eq!(events_3.len(), 1);
6481         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6482                 match events_3[0] {
6483                         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 } } => {
6484                                 assert!(update_add_htlcs.is_empty());
6485                                 assert!(update_fulfill_htlcs.is_empty());
6486                                 assert!(update_fail_htlcs.is_empty());
6487                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6488                                 assert!(update_fee.is_none());
6489                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6490                         },
6491                         _ => panic!("Unexpected event"),
6492                 }
6493         };
6494
6495         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6496
6497         check_added_monitors!(nodes[1], 0);
6498         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6499         expect_pending_htlcs_forwardable!(nodes[1]);
6500         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6501         assert_eq!(events_4.len(), 1);
6502
6503         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6504         match events_4[0] {
6505                 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, .. } } => {
6506                         assert!(update_add_htlcs.is_empty());
6507                         assert!(update_fulfill_htlcs.is_empty());
6508                         assert_eq!(update_fail_htlcs.len(), 1);
6509                         assert!(update_fail_malformed_htlcs.is_empty());
6510                         assert!(update_fee.is_none());
6511                 },
6512                 _ => panic!("Unexpected event"),
6513         };
6514
6515         check_added_monitors!(nodes[1], 1);
6516 }
6517
6518 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6519         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6520         // 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
6521         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6522
6523         let chanmon_cfgs = create_chanmon_cfgs(2);
6524         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6525         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6526         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6527         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6528
6529         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6530
6531         // We route 2 dust-HTLCs between A and B
6532         let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6533         let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6534         route_payment(&nodes[0], &[&nodes[1]], 1000000);
6535
6536         // Cache one local commitment tx as previous
6537         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6538
6539         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6540         assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2, &None));
6541         check_added_monitors!(nodes[1], 0);
6542         expect_pending_htlcs_forwardable!(nodes[1]);
6543         check_added_monitors!(nodes[1], 1);
6544
6545         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6546         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6547         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6548         check_added_monitors!(nodes[0], 1);
6549
6550         // Cache one local commitment tx as lastest
6551         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6552
6553         let events = nodes[0].node.get_and_clear_pending_msg_events();
6554         match events[0] {
6555                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6556                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6557                 },
6558                 _ => panic!("Unexpected event"),
6559         }
6560         match events[1] {
6561                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6562                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6563                 },
6564                 _ => panic!("Unexpected event"),
6565         }
6566
6567         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6568         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6569         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6570
6571         if announce_latest {
6572                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_last_commitment_tx[0].clone()]}, 1);
6573         } else {
6574                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_prev_commitment_tx[0].clone()]}, 1);
6575         }
6576
6577         check_closed_broadcast!(nodes[0], false);
6578         check_added_monitors!(nodes[0], 1);
6579
6580         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6581         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 1, true,  header.bitcoin_hash());
6582         let events = nodes[0].node.get_and_clear_pending_events();
6583         // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
6584         assert_eq!(events.len(), 2);
6585         let mut first_failed = false;
6586         for event in events {
6587                 match event {
6588                         Event::PaymentFailed { payment_hash, .. } => {
6589                                 if payment_hash == payment_hash_1 {
6590                                         assert!(!first_failed);
6591                                         first_failed = true;
6592                                 } else {
6593                                         assert_eq!(payment_hash, payment_hash_2);
6594                                 }
6595                         }
6596                         _ => panic!("Unexpected event"),
6597                 }
6598         }
6599 }
6600
6601 #[test]
6602 fn test_failure_delay_dust_htlc_local_commitment() {
6603         do_test_failure_delay_dust_htlc_local_commitment(true);
6604         do_test_failure_delay_dust_htlc_local_commitment(false);
6605 }
6606
6607 #[test]
6608 fn test_no_failure_dust_htlc_local_commitment() {
6609         // Transaction filters for failing back dust htlc based on local commitment txn infos has been
6610         // prone to error, we test here that a dummy transaction don't fail them.
6611
6612         let chanmon_cfgs = create_chanmon_cfgs(2);
6613         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6614         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6615         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6616         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6617
6618         // Rebalance a bit
6619         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
6620
6621         let as_dust_limit = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6622         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6623
6624         // We route 2 dust-HTLCs between A and B
6625         let (preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6626         let (preimage_2, _) = route_payment(&nodes[1], &[&nodes[0]], as_dust_limit*1000);
6627
6628         // Build a dummy invalid transaction trying to spend a commitment tx
6629         let input = TxIn {
6630                 previous_output: BitcoinOutPoint { txid: chan.3.txid(), vout: 0 },
6631                 script_sig: Script::new(),
6632                 sequence: 0,
6633                 witness: Vec::new(),
6634         };
6635
6636         let outp = TxOut {
6637                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
6638                 value: 10000,
6639         };
6640
6641         let dummy_tx = Transaction {
6642                 version: 2,
6643                 lock_time: 0,
6644                 input: vec![input],
6645                 output: vec![outp]
6646         };
6647
6648         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6649         nodes[0].chan_monitor.simple_monitor.block_connected(&header, 1, &[&dummy_tx], &[1;1]);
6650         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6651         assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
6652         // We broadcast a few more block to check everything is all right
6653         connect_blocks(&nodes[0].block_notifier, 20, 1, true,  header.bitcoin_hash());
6654         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6655         assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
6656
6657         claim_payment(&nodes[0], &vec!(&nodes[1])[..], preimage_1, bs_dust_limit*1000);
6658         claim_payment(&nodes[1], &vec!(&nodes[0])[..], preimage_2, as_dust_limit*1000);
6659 }
6660
6661 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6662         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6663         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6664         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6665         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6666         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6667         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6668
6669         let chanmon_cfgs = create_chanmon_cfgs(3);
6670         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6671         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6672         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6673         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6674
6675         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6676
6677         let (_payment_preimage_1, dust_hash) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6678         let (_payment_preimage_2, non_dust_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6679
6680         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6681         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6682
6683         // We revoked bs_commitment_tx
6684         if revoked {
6685                 let (payment_preimage_3, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6686                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 1_000_000);
6687         }
6688
6689         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6690         let mut timeout_tx = Vec::new();
6691         if local {
6692                 // We fail dust-HTLC 1 by broadcast of local commitment tx
6693                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_commitment_tx[0].clone()]}, 1);
6694                 check_closed_broadcast!(nodes[0], false);
6695                 check_added_monitors!(nodes[0], 1);
6696                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6697                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6698                 let parent_hash  = connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 2, true, header.bitcoin_hash());
6699                 expect_payment_failed!(nodes[0], dust_hash, true);
6700                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6701                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6702                 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6703                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6704                 nodes[0].block_notifier.block_connected(&Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
6705                 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6706                 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 8, true, header_3.bitcoin_hash());
6707                 expect_payment_failed!(nodes[0], non_dust_hash, true);
6708         } else {
6709                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6710                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![bs_commitment_tx[0].clone()]}, 1);
6711                 check_closed_broadcast!(nodes[0], false);
6712                 check_added_monitors!(nodes[0], 1);
6713                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6714                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6715                 let parent_hash  = connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 2, true, header.bitcoin_hash());
6716                 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6717                 if !revoked {
6718                         expect_payment_failed!(nodes[0], dust_hash, true);
6719                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6720                         // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
6721                         nodes[0].block_notifier.block_connected(&Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
6722                         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6723                         let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6724                         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 8, true, header_3.bitcoin_hash());
6725                         expect_payment_failed!(nodes[0], non_dust_hash, true);
6726                 } else {
6727                         // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
6728                         // commitment tx
6729                         let events = nodes[0].node.get_and_clear_pending_events();
6730                         assert_eq!(events.len(), 2);
6731                         let first;
6732                         match events[0] {
6733                                 Event::PaymentFailed { payment_hash, .. } => {
6734                                         if payment_hash == dust_hash { first = true; }
6735                                         else { first = false; }
6736                                 },
6737                                 _ => panic!("Unexpected event"),
6738                         }
6739                         match events[1] {
6740                                 Event::PaymentFailed { payment_hash, .. } => {
6741                                         if first { assert_eq!(payment_hash, non_dust_hash); }
6742                                         else { assert_eq!(payment_hash, dust_hash); }
6743                                 },
6744                                 _ => panic!("Unexpected event"),
6745                         }
6746                 }
6747         }
6748 }
6749
6750 #[test]
6751 fn test_sweep_outbound_htlc_failure_update() {
6752         do_test_sweep_outbound_htlc_failure_update(false, true);
6753         do_test_sweep_outbound_htlc_failure_update(false, false);
6754         do_test_sweep_outbound_htlc_failure_update(true, false);
6755 }
6756
6757 #[test]
6758 fn test_upfront_shutdown_script() {
6759         // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
6760         // enforce it at shutdown message
6761
6762         let mut config = UserConfig::default();
6763         config.channel_options.announced_channel = true;
6764         config.peer_channel_config_limits.force_announced_channel_preference = false;
6765         config.channel_options.commit_upfront_shutdown_pubkey = false;
6766         let user_cfgs = [None, Some(config), None];
6767         let chanmon_cfgs = create_chanmon_cfgs(3);
6768         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6769         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
6770         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6771
6772         // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
6773         let flags = InitFeatures::known();
6774         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
6775         nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6776         let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
6777         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6778         // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that  we disconnect peer
6779         nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
6780         assert_eq!(check_closed_broadcast!(nodes[2], true).unwrap().data, "Got shutdown request with a scriptpubkey which did not match their previous scriptpubkey");
6781         check_added_monitors!(nodes[2], 1);
6782
6783         // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
6784         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
6785         nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6786         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
6787         // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
6788         nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
6789         let events = nodes[2].node.get_and_clear_pending_msg_events();
6790         assert_eq!(events.len(), 1);
6791         match events[0] {
6792                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
6793                 _ => panic!("Unexpected event"),
6794         }
6795
6796         // We test that if case of peer non-signaling we don't enforce committed script at channel opening
6797         let flags_no = InitFeatures::known().clear_upfront_shutdown_script();
6798         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone());
6799         nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6800         let mut node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
6801         node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6802         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_1_shutdown);
6803         let events = nodes[1].node.get_and_clear_pending_msg_events();
6804         assert_eq!(events.len(), 1);
6805         match events[0] {
6806                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
6807                 _ => panic!("Unexpected event"),
6808         }
6809
6810         // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
6811         // channel smoothly, opt-out is from channel initiator here
6812         let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone());
6813         nodes[1].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6814         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
6815         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6816         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
6817         let events = nodes[0].node.get_and_clear_pending_msg_events();
6818         assert_eq!(events.len(), 1);
6819         match events[0] {
6820                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
6821                 _ => panic!("Unexpected event"),
6822         }
6823
6824         //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
6825         //// channel smoothly
6826         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone());
6827         nodes[1].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6828         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
6829         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6830         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
6831         let events = nodes[0].node.get_and_clear_pending_msg_events();
6832         assert_eq!(events.len(), 2);
6833         match events[0] {
6834                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
6835                 _ => panic!("Unexpected event"),
6836         }
6837         match events[1] {
6838                 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
6839                 _ => panic!("Unexpected event"),
6840         }
6841 }
6842
6843 #[test]
6844 fn test_user_configurable_csv_delay() {
6845         // We test our channel constructors yield errors when we pass them absurd csv delay
6846
6847         let mut low_our_to_self_config = UserConfig::default();
6848         low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
6849         let mut high_their_to_self_config = UserConfig::default();
6850         high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
6851         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
6852         let chanmon_cfgs = create_chanmon_cfgs(2);
6853         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6854         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
6855         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6856
6857         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
6858         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())));
6859         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) {
6860                 match error {
6861                         APIError::APIMisuseError { err } => { assert_eq!(err, "Configured with an unreasonable our_to_self_delay putting user funds at risks"); },
6862                         _ => panic!("Unexpected event"),
6863                 }
6864         } else { assert!(false) }
6865
6866         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
6867         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6868         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6869         open_channel.to_self_delay = 200;
6870         if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &keys_manager, nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel, 0, Arc::new(test_utils::TestLogger::new()), &low_our_to_self_config) {
6871                 match error {
6872                         ChannelError::Close(err) => { assert_eq!(err, "Configured with an unreasonable our_to_self_delay putting user funds at risks"); },
6873                         _ => panic!("Unexpected event"),
6874                 }
6875         } else { assert!(false); }
6876
6877         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
6878         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6879         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()));
6880         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6881         accept_channel.to_self_delay = 200;
6882         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
6883         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
6884                 match action {
6885                         &ErrorAction::SendErrorMessage { ref msg } => {
6886                                 assert_eq!(msg.data,"They wanted our payments to be delayed by a needlessly long period");
6887                         },
6888                         _ => { assert!(false); }
6889                 }
6890         } else { assert!(false); }
6891
6892         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
6893         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6894         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6895         open_channel.to_self_delay = 200;
6896         if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &keys_manager, nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel, 0, Arc::new(test_utils::TestLogger::new()), &high_their_to_self_config) {
6897                 match error {
6898                         ChannelError::Close(err) => { assert_eq!(err, "They wanted our payments to be delayed by a needlessly long period"); },
6899                         _ => panic!("Unexpected event"),
6900                 }
6901         } else { assert!(false); }
6902 }
6903
6904 #[test]
6905 fn test_data_loss_protect() {
6906         // We want to be sure that :
6907         // * we don't broadcast our Local Commitment Tx in case of fallen behind
6908         // * we close channel in case of detecting other being fallen behind
6909         // * we are able to claim our own outputs thanks to to_remote being static
6910         let keys_manager;
6911         let fee_estimator;
6912         let tx_broadcaster;
6913         let monitor;
6914         let node_state_0;
6915         let chanmon_cfgs = create_chanmon_cfgs(2);
6916         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6917         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6918         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6919
6920         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6921
6922         // Cache node A state before any channel update
6923         let previous_node_state = nodes[0].node.encode();
6924         let mut previous_chan_monitor_state = test_utils::TestVecWriter(Vec::new());
6925         nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut previous_chan_monitor_state).unwrap();
6926
6927         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
6928         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
6929
6930         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6931         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6932
6933         // Restore node A from previous state
6934         let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::with_id(format!("node {}", 0)));
6935         let mut chan_monitor = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut ::std::io::Cursor::new(previous_chan_monitor_state.0), Arc::clone(&logger)).unwrap().1;
6936         let chain_monitor = Arc::new(ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
6937         tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
6938         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
6939         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::clone(&logger));
6940         monitor = test_utils::TestChannelMonitor::new(chain_monitor.clone(), &tx_broadcaster, logger.clone(), &fee_estimator);
6941         node_state_0 = {
6942                 let mut channel_monitors = HashMap::new();
6943                 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chan_monitor);
6944                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>)>::read(&mut ::std::io::Cursor::new(previous_node_state), ChannelManagerReadArgs {
6945                         keys_manager: &keys_manager,
6946                         fee_estimator: &fee_estimator,
6947                         monitor: &monitor,
6948                         logger: Arc::clone(&logger),
6949                         tx_broadcaster: &tx_broadcaster,
6950                         default_config: UserConfig::default(),
6951                         channel_monitors: &mut channel_monitors,
6952                 }).unwrap().1
6953         };
6954         nodes[0].node = &node_state_0;
6955         assert!(monitor.add_monitor(OutPoint { txid: chan.3.txid(), index: 0 }, chan_monitor).is_ok());
6956         nodes[0].chan_monitor = &monitor;
6957         nodes[0].chain_monitor = chain_monitor;
6958
6959         nodes[0].block_notifier = BlockNotifier::new(nodes[0].chain_monitor.clone());
6960         nodes[0].block_notifier.register_listener(&nodes[0].chan_monitor.simple_monitor);
6961         nodes[0].block_notifier.register_listener(nodes[0].node);
6962
6963         check_added_monitors!(nodes[0], 1);
6964
6965         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6966         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6967
6968         let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6969
6970         // Check we don't broadcast any transactions following learning of per_commitment_point from B
6971         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
6972         check_added_monitors!(nodes[0], 1);
6973
6974         {
6975                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
6976                 assert_eq!(node_txn.len(), 0);
6977         }
6978
6979         let mut reestablish_1 = Vec::with_capacity(1);
6980         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
6981                 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
6982                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
6983                         reestablish_1.push(msg.clone());
6984                 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
6985                 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
6986                         match action {
6987                                 &ErrorAction::SendErrorMessage { ref msg } => {
6988                                         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");
6989                                 },
6990                                 _ => panic!("Unexpected event!"),
6991                         }
6992                 } else {
6993                         panic!("Unexpected event")
6994                 }
6995         }
6996
6997         // Check we close channel detecting A is fallen-behind
6998         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6999         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7000         check_added_monitors!(nodes[1], 1);
7001
7002
7003         // Check A is able to claim to_remote output
7004         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7005         assert_eq!(node_txn.len(), 1);
7006         check_spends!(node_txn[0], chan.3);
7007         assert_eq!(node_txn[0].output.len(), 2);
7008         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
7009         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()]}, 0);
7010         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 0, true, header.bitcoin_hash());
7011         let spend_txn = check_spendable_outputs!(nodes[0], 1);
7012         assert_eq!(spend_txn.len(), 1);
7013         check_spends!(spend_txn[0], node_txn[0]);
7014 }
7015
7016 #[test]
7017 fn test_check_htlc_underpaying() {
7018         // Send payment through A -> B but A is maliciously
7019         // sending a probe payment (i.e less than expected value0
7020         // to B, B should refuse payment.
7021
7022         let chanmon_cfgs = create_chanmon_cfgs(2);
7023         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7024         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7025         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7026
7027         // Create some initial channels
7028         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7029
7030         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 10_000);
7031
7032         // Node 3 is expecting payment of 100_000 but receive 10_000,
7033         // fail htlc like we didn't know the preimage.
7034         nodes[1].node.claim_funds(payment_preimage, &None, 100_000);
7035         nodes[1].node.process_pending_htlc_forwards();
7036
7037         let events = nodes[1].node.get_and_clear_pending_msg_events();
7038         assert_eq!(events.len(), 1);
7039         let (update_fail_htlc, commitment_signed) = match events[0] {
7040                 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 } } => {
7041                         assert!(update_add_htlcs.is_empty());
7042                         assert!(update_fulfill_htlcs.is_empty());
7043                         assert_eq!(update_fail_htlcs.len(), 1);
7044                         assert!(update_fail_malformed_htlcs.is_empty());
7045                         assert!(update_fee.is_none());
7046                         (update_fail_htlcs[0].clone(), commitment_signed)
7047                 },
7048                 _ => panic!("Unexpected event"),
7049         };
7050         check_added_monitors!(nodes[1], 1);
7051
7052         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7053         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7054
7055         // 10_000 msat as u64, followed by a height of 99 as u32
7056         let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7057         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(99));
7058         expect_payment_failed!(nodes[0], payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7059         nodes[1].node.get_and_clear_pending_events();
7060 }
7061
7062 #[test]
7063 fn test_announce_disable_channels() {
7064         // Create 2 channels between A and B. Disconnect B. Call timer_chan_freshness_every_min and check for generated
7065         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7066
7067         let chanmon_cfgs = create_chanmon_cfgs(2);
7068         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7069         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7070         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7071
7072         let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7073         let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7074         let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7075
7076         // Disconnect peers
7077         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7078         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7079
7080         nodes[0].node.timer_chan_freshness_every_min(); // dirty -> stagged
7081         nodes[0].node.timer_chan_freshness_every_min(); // staged -> fresh
7082         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7083         assert_eq!(msg_events.len(), 3);
7084         for e in msg_events {
7085                 match e {
7086                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7087                                 let short_id = msg.contents.short_channel_id;
7088                                 // Check generated channel_update match list in PendingChannelUpdate
7089                                 if short_id != short_id_1 && short_id != short_id_2 && short_id != short_id_3 {
7090                                         panic!("Generated ChannelUpdate for wrong chan!");
7091                                 }
7092                         },
7093                         _ => panic!("Unexpected event"),
7094                 }
7095         }
7096         // Reconnect peers
7097         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7098         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7099         assert_eq!(reestablish_1.len(), 3);
7100         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7101         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7102         assert_eq!(reestablish_2.len(), 3);
7103
7104         // Reestablish chan_1
7105         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7106         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7107         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7108         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7109         // Reestablish chan_2
7110         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7111         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7112         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7113         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7114         // Reestablish chan_3
7115         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7116         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7117         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7118         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7119
7120         nodes[0].node.timer_chan_freshness_every_min();
7121         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7122 }
7123
7124 #[test]
7125 fn test_bump_penalty_txn_on_revoked_commitment() {
7126         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7127         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7128
7129         let chanmon_cfgs = create_chanmon_cfgs(2);
7130         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7131         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7132         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7133
7134         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7135         let logger = Arc::new(test_utils::TestLogger::new());
7136
7137
7138         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7139         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
7140         let route = get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[0].node.get_our_node_id(), None, &Vec::new(), 3000000, 30, logger.clone()).unwrap();
7141         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7142
7143         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7144         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7145         assert_eq!(revoked_txn[0].output.len(), 4);
7146         assert_eq!(revoked_txn[0].input.len(), 1);
7147         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7148         let revoked_txid = revoked_txn[0].txid();
7149
7150         let mut penalty_sum = 0;
7151         for outp in revoked_txn[0].output.iter() {
7152                 if outp.script_pubkey.is_v0_p2wsh() {
7153                         penalty_sum += outp.value;
7154                 }
7155         }
7156
7157         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7158         let header_114 = connect_blocks(&nodes[1].block_notifier, 114, 0, false, Default::default());
7159
7160         // Actually revoke tx by claiming a HTLC
7161         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7162         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7163         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_txn[0].clone()] }, 115);
7164         check_added_monitors!(nodes[1], 1);
7165
7166         // One or more justice tx should have been broadcast, check it
7167         let penalty_1;
7168         let feerate_1;
7169         {
7170                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7171                 assert_eq!(node_txn.len(), 3); // justice tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout (broadcasted from ChannelManager)
7172                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7173                 assert_eq!(node_txn[0].output.len(), 1);
7174                 check_spends!(node_txn[0], revoked_txn[0]);
7175                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7176                 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7177                 penalty_1 = node_txn[0].txid();
7178                 node_txn.clear();
7179         };
7180
7181         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7182         let header = connect_blocks(&nodes[1].block_notifier, 3, 115,  true, header.bitcoin_hash());
7183         let mut penalty_2 = penalty_1;
7184         let mut feerate_2 = 0;
7185         {
7186                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7187                 assert_eq!(node_txn.len(), 1);
7188                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7189                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7190                         assert_eq!(node_txn[0].output.len(), 1);
7191                         check_spends!(node_txn[0], revoked_txn[0]);
7192                         penalty_2 = node_txn[0].txid();
7193                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7194                         assert_ne!(penalty_2, penalty_1);
7195                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7196                         feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7197                         // Verify 25% bump heuristic
7198                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7199                         node_txn.clear();
7200                 }
7201         }
7202         assert_ne!(feerate_2, 0);
7203
7204         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7205         connect_blocks(&nodes[1].block_notifier, 3, 118, true, header);
7206         let penalty_3;
7207         let mut feerate_3 = 0;
7208         {
7209                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7210                 assert_eq!(node_txn.len(), 1);
7211                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7212                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7213                         assert_eq!(node_txn[0].output.len(), 1);
7214                         check_spends!(node_txn[0], revoked_txn[0]);
7215                         penalty_3 = node_txn[0].txid();
7216                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7217                         assert_ne!(penalty_3, penalty_2);
7218                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7219                         feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7220                         // Verify 25% bump heuristic
7221                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7222                         node_txn.clear();
7223                 }
7224         }
7225         assert_ne!(feerate_3, 0);
7226
7227         nodes[1].node.get_and_clear_pending_events();
7228         nodes[1].node.get_and_clear_pending_msg_events();
7229 }
7230
7231 #[test]
7232 fn test_bump_penalty_txn_on_revoked_htlcs() {
7233         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7234         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7235
7236         let chanmon_cfgs = create_chanmon_cfgs(2);
7237         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7238         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7239         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7240
7241         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7242         // Lock HTLC in both directions
7243         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3_000_000).0;
7244         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7245
7246         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7247         assert_eq!(revoked_local_txn[0].input.len(), 1);
7248         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7249
7250         // Revoke local commitment tx
7251         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7252
7253         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7254         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7255         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
7256         check_closed_broadcast!(nodes[1], false);
7257         check_added_monitors!(nodes[1], 1);
7258
7259         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7260         assert_eq!(revoked_htlc_txn.len(), 4);
7261         if revoked_htlc_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7262                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7263                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7264                 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7265                 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7266                 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7267         } else if revoked_htlc_txn[1].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7268                 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7269                 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7270                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7271                 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7272                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7273         }
7274
7275         // Broadcast set of revoked txn on A
7276         let header_128 = connect_blocks(&nodes[0].block_notifier, 128, 0, true, header.bitcoin_hash());
7277         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7278
7279         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7280         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);
7281         let first;
7282         let feerate_1;
7283         let penalty_txn;
7284         {
7285                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7286                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7287                 // Verify claim tx are spending revoked HTLC txn
7288                 assert_eq!(node_txn[4].input.len(), 2);
7289                 assert_eq!(node_txn[4].output.len(), 1);
7290                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7291                 first = node_txn[4].txid();
7292                 // Store both feerates for later comparison
7293                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[4].output[0].value;
7294                 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7295                 penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7296                 node_txn.clear();
7297         }
7298
7299         // Connect three more block to see if bumped penalty are issued for HTLC txn
7300         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7301         nodes[0].block_notifier.block_connected(&Block { header: header_130, txdata: penalty_txn }, 130);
7302         {
7303                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7304                 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7305
7306                 check_spends!(node_txn[0], revoked_local_txn[0]);
7307                 check_spends!(node_txn[1], revoked_local_txn[0]);
7308
7309                 node_txn.clear();
7310         };
7311
7312         // Few more blocks to confirm penalty txn
7313         let header_135 = connect_blocks(&nodes[0].block_notifier, 5, 130, true, header_130.bitcoin_hash());
7314         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7315         let header_144 = connect_blocks(&nodes[0].block_notifier, 9, 135, true, header_135);
7316         let node_txn = {
7317                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7318                 assert_eq!(node_txn.len(), 1);
7319
7320                 assert_eq!(node_txn[0].input.len(), 2);
7321                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7322                 // Verify bumped tx is different and 25% bump heuristic
7323                 assert_ne!(first, node_txn[0].txid());
7324                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7325                 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7326                 assert!(feerate_2 * 100 > feerate_1 * 125);
7327                 let txn = vec![node_txn[0].clone()];
7328                 node_txn.clear();
7329                 txn
7330         };
7331         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7332         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7333         nodes[0].block_notifier.block_connected(&Block { header: header_145, txdata: node_txn }, 145);
7334         connect_blocks(&nodes[0].block_notifier, 20, 145, true, header_145.bitcoin_hash());
7335         {
7336                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7337                 // We verify than no new transaction has been broadcast because previously
7338                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7339                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7340                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7341                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7342                 // up bumped justice generation.
7343                 assert_eq!(node_txn.len(), 0);
7344                 node_txn.clear();
7345         }
7346         check_closed_broadcast!(nodes[0], false);
7347         check_added_monitors!(nodes[0], 1);
7348 }
7349
7350 #[test]
7351 fn test_bump_penalty_txn_on_remote_commitment() {
7352         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7353         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7354
7355         // Create 2 HTLCs
7356         // Provide preimage for one
7357         // Check aggregation
7358
7359         let chanmon_cfgs = create_chanmon_cfgs(2);
7360         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7361         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7362         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7363
7364         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7365         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7366         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7367
7368         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7369         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7370         assert_eq!(remote_txn[0].output.len(), 4);
7371         assert_eq!(remote_txn[0].input.len(), 1);
7372         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7373
7374         // Claim a HTLC without revocation (provide B monitor with preimage)
7375         nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000);
7376         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7377         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
7378         check_added_monitors!(nodes[1], 2);
7379
7380         // One or more claim tx should have been broadcast, check it
7381         let timeout;
7382         let preimage;
7383         let feerate_timeout;
7384         let feerate_preimage;
7385         {
7386                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7387                 assert_eq!(node_txn.len(), 5); // 2 * claim tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout + local HTLC-success (broadcasted from ChannelManager)
7388                 assert_eq!(node_txn[0].input.len(), 1);
7389                 assert_eq!(node_txn[1].input.len(), 1);
7390                 check_spends!(node_txn[0], remote_txn[0]);
7391                 check_spends!(node_txn[1], remote_txn[0]);
7392                 check_spends!(node_txn[2], chan.3);
7393                 check_spends!(node_txn[3], node_txn[2]);
7394                 check_spends!(node_txn[4], node_txn[2]);
7395                 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7396                         timeout = node_txn[0].txid();
7397                         let index = node_txn[0].input[0].previous_output.vout;
7398                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7399                         feerate_timeout = fee * 1000 / node_txn[0].get_weight() as u64;
7400
7401                         preimage = node_txn[1].txid();
7402                         let index = node_txn[1].input[0].previous_output.vout;
7403                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7404                         feerate_preimage = fee * 1000 / node_txn[1].get_weight() as u64;
7405                 } else {
7406                         timeout = node_txn[1].txid();
7407                         let index = node_txn[1].input[0].previous_output.vout;
7408                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7409                         feerate_timeout = fee * 1000 / node_txn[1].get_weight() as u64;
7410
7411                         preimage = node_txn[0].txid();
7412                         let index = node_txn[0].input[0].previous_output.vout;
7413                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7414                         feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7415                 }
7416                 node_txn.clear();
7417         };
7418         assert_ne!(feerate_timeout, 0);
7419         assert_ne!(feerate_preimage, 0);
7420
7421         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7422         connect_blocks(&nodes[1].block_notifier, 15, 1,  true, header.bitcoin_hash());
7423         {
7424                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7425                 assert_eq!(node_txn.len(), 2);
7426                 assert_eq!(node_txn[0].input.len(), 1);
7427                 assert_eq!(node_txn[1].input.len(), 1);
7428                 check_spends!(node_txn[0], remote_txn[0]);
7429                 check_spends!(node_txn[1], remote_txn[0]);
7430                 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7431                         let index = node_txn[0].input[0].previous_output.vout;
7432                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7433                         let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7434                         assert!(new_feerate * 100 > feerate_timeout * 125);
7435                         assert_ne!(timeout, node_txn[0].txid());
7436
7437                         let index = node_txn[1].input[0].previous_output.vout;
7438                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7439                         let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7440                         assert!(new_feerate * 100 > feerate_preimage * 125);
7441                         assert_ne!(preimage, node_txn[1].txid());
7442                 } else {
7443                         let index = node_txn[1].input[0].previous_output.vout;
7444                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7445                         let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7446                         assert!(new_feerate * 100 > feerate_timeout * 125);
7447                         assert_ne!(timeout, node_txn[1].txid());
7448
7449                         let index = node_txn[0].input[0].previous_output.vout;
7450                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7451                         let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7452                         assert!(new_feerate * 100 > feerate_preimage * 125);
7453                         assert_ne!(preimage, node_txn[0].txid());
7454                 }
7455                 node_txn.clear();
7456         }
7457
7458         nodes[1].node.get_and_clear_pending_events();
7459         nodes[1].node.get_and_clear_pending_msg_events();
7460 }
7461
7462 #[test]
7463 fn test_set_outpoints_partial_claiming() {
7464         // - remote party claim tx, new bump tx
7465         // - disconnect remote claiming tx, new bump
7466         // - disconnect tx, see no tx anymore
7467         let chanmon_cfgs = create_chanmon_cfgs(2);
7468         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7469         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7470         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7471
7472         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7473         let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7474         let payment_preimage_2 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7475
7476         // Remote commitment txn with 4 outputs: to_local, to_remote, 2 outgoing HTLC
7477         let remote_txn = get_local_commitment_txn!(nodes[1], chan.2);
7478         assert_eq!(remote_txn.len(), 3);
7479         assert_eq!(remote_txn[0].output.len(), 4);
7480         assert_eq!(remote_txn[0].input.len(), 1);
7481         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7482         check_spends!(remote_txn[1], remote_txn[0]);
7483         check_spends!(remote_txn[2], remote_txn[0]);
7484
7485         // Connect blocks on node A to advance height towards TEST_FINAL_CLTV
7486         let prev_header_100 = connect_blocks(&nodes[1].block_notifier, 100, 0, false, Default::default());
7487         // Provide node A with both preimage
7488         nodes[0].node.claim_funds(payment_preimage_1, &None, 3_000_000);
7489         nodes[0].node.claim_funds(payment_preimage_2, &None, 3_000_000);
7490         check_added_monitors!(nodes[0], 2);
7491         nodes[0].node.get_and_clear_pending_events();
7492         nodes[0].node.get_and_clear_pending_msg_events();
7493
7494         // Connect blocks on node A commitment transaction
7495         let header = BlockHeader { version: 0x20000000, prev_blockhash: prev_header_100, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7496         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 101);
7497         check_closed_broadcast!(nodes[0], false);
7498         check_added_monitors!(nodes[0], 1);
7499         // Verify node A broadcast tx claiming both HTLCs
7500         {
7501                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7502                 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-Success*2
7503                 assert_eq!(node_txn.len(), 4);
7504                 check_spends!(node_txn[0], remote_txn[0]);
7505                 check_spends!(node_txn[1], chan.3);
7506                 check_spends!(node_txn[2], node_txn[1]);
7507                 check_spends!(node_txn[3], node_txn[1]);
7508                 assert_eq!(node_txn[0].input.len(), 2);
7509                 node_txn.clear();
7510         }
7511
7512         // Connect blocks on node B
7513         connect_blocks(&nodes[1].block_notifier, 135, 0, false, Default::default());
7514         check_closed_broadcast!(nodes[1], false);
7515         check_added_monitors!(nodes[1], 1);
7516         // Verify node B broadcast 2 HTLC-timeout txn
7517         let partial_claim_tx = {
7518                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7519                 assert_eq!(node_txn.len(), 3);
7520                 check_spends!(node_txn[1], node_txn[0]);
7521                 check_spends!(node_txn[2], node_txn[0]);
7522                 assert_eq!(node_txn[1].input.len(), 1);
7523                 assert_eq!(node_txn[2].input.len(), 1);
7524                 node_txn[1].clone()
7525         };
7526
7527         // Broadcast partial claim on node A, should regenerate a claiming tx with HTLC dropped
7528         let header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7529         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![partial_claim_tx.clone()] }, 102);
7530         {
7531                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7532                 assert_eq!(node_txn.len(), 1);
7533                 check_spends!(node_txn[0], remote_txn[0]);
7534                 assert_eq!(node_txn[0].input.len(), 1); //dropped HTLC
7535                 node_txn.clear();
7536         }
7537         nodes[0].node.get_and_clear_pending_msg_events();
7538
7539         // Disconnect last block on node A, should regenerate a claiming tx with HTLC dropped
7540         nodes[0].block_notifier.block_disconnected(&header, 102);
7541         {
7542                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7543                 assert_eq!(node_txn.len(), 1);
7544                 check_spends!(node_txn[0], remote_txn[0]);
7545                 assert_eq!(node_txn[0].input.len(), 2); //resurrected HTLC
7546                 node_txn.clear();
7547         }
7548
7549         //// Disconnect one more block and then reconnect multiple no transaction should be generated
7550         nodes[0].block_notifier.block_disconnected(&header, 101);
7551         connect_blocks(&nodes[1].block_notifier, 15, 101, false, prev_header_100);
7552         {
7553                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7554                 assert_eq!(node_txn.len(), 0);
7555                 node_txn.clear();
7556         }
7557 }
7558
7559 #[test]
7560 fn test_counterparty_raa_skip_no_crash() {
7561         // Previously, if our counterparty sent two RAAs in a row without us having provided a
7562         // commitment transaction, we would have happily carried on and provided them the next
7563         // commitment transaction based on one RAA forward. This would probably eventually have led to
7564         // channel closure, but it would not have resulted in funds loss. Still, our
7565         // EnforcingChannelKeys would have paniced as it doesn't like jumps into the future. Here, we
7566         // check simply that the channel is closed in response to such an RAA, but don't check whether
7567         // we decide to punish our counterparty for revoking their funds (as we don't currently
7568         // implement that).
7569         let chanmon_cfgs = create_chanmon_cfgs(2);
7570         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7571         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7572         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7573         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
7574
7575         let commitment_seed = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&channel_id).unwrap().local_keys.commitment_seed().clone();
7576         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7577         let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7578                 &SecretKey::from_slice(&chan_utils::build_commitment_secret(&commitment_seed, INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7579         let per_commitment_secret = chan_utils::build_commitment_secret(&commitment_seed, INITIAL_COMMITMENT_NUMBER);
7580
7581         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7582                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
7583         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7584         check_added_monitors!(nodes[1], 1);
7585 }
7586
7587 #[test]
7588 fn test_bump_txn_sanitize_tracking_maps() {
7589         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7590         // verify we clean then right after expiration of ANTI_REORG_DELAY.
7591
7592         let chanmon_cfgs = create_chanmon_cfgs(2);
7593         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7594         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7595         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7596
7597         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7598         // Lock HTLC in both directions
7599         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
7600         route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
7601
7602         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7603         assert_eq!(revoked_local_txn[0].input.len(), 1);
7604         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7605
7606         // Revoke local commitment tx
7607         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 9_000_000);
7608
7609         // Broadcast set of revoked txn on A
7610         let header_128 = connect_blocks(&nodes[0].block_notifier, 128, 0,  false, Default::default());
7611         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7612
7613         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7614         nodes[0].block_notifier.block_connected(&Block { header: header_129, txdata: vec![revoked_local_txn[0].clone()] }, 129);
7615         check_closed_broadcast!(nodes[0], false);
7616         check_added_monitors!(nodes[0], 1);
7617         let penalty_txn = {
7618                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7619                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
7620                 check_spends!(node_txn[0], revoked_local_txn[0]);
7621                 check_spends!(node_txn[1], revoked_local_txn[0]);
7622                 check_spends!(node_txn[2], revoked_local_txn[0]);
7623                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7624                 node_txn.clear();
7625                 penalty_txn
7626         };
7627         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7628         nodes[0].block_notifier.block_connected(&Block { header: header_130, txdata: penalty_txn }, 130);
7629         connect_blocks(&nodes[0].block_notifier, 5, 130,  false, header_130.bitcoin_hash());
7630         {
7631                 let monitors = nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap();
7632                 if let Some(monitor) = monitors.get(&OutPoint::new(chan.3.txid(), 0)) {
7633                         assert!(monitor.onchain_tx_handler.pending_claim_requests.is_empty());
7634                         assert!(monitor.onchain_tx_handler.claimable_outpoints.is_empty());
7635                 }
7636         }
7637 }
7638
7639 #[test]
7640 fn test_override_channel_config() {
7641         let chanmon_cfgs = create_chanmon_cfgs(2);
7642         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7643         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7644         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7645
7646         // Node0 initiates a channel to node1 using the override config.
7647         let mut override_config = UserConfig::default();
7648         override_config.own_channel_config.our_to_self_delay = 200;
7649
7650         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7651
7652         // Assert the channel created by node0 is using the override config.
7653         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7654         assert_eq!(res.channel_flags, 0);
7655         assert_eq!(res.to_self_delay, 200);
7656 }
7657
7658 #[test]
7659 fn test_override_0msat_htlc_minimum() {
7660         let mut zero_config = UserConfig::default();
7661         zero_config.own_channel_config.our_htlc_minimum_msat = 0;
7662         let chanmon_cfgs = create_chanmon_cfgs(2);
7663         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7664         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7665         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7666
7667         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7668         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7669         assert_eq!(res.htlc_minimum_msat, 1);
7670
7671         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
7672         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7673         assert_eq!(res.htlc_minimum_msat, 1);
7674 }
7675
7676 #[test]
7677 fn test_simple_payment_secret() {
7678         // Simple test of sending a payment with a payment_secret present. This does not use any AMP
7679         // features, however.
7680         let chanmon_cfgs = create_chanmon_cfgs(3);
7681         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7682         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7683         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7684
7685         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7686         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
7687         let logger = Arc::new(test_utils::TestLogger::new());
7688
7689         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
7690         let payment_secret = PaymentSecret([0xdb; 32]);
7691         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
7692         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, logger.clone()).unwrap();
7693         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2]]], 100000, payment_hash, Some(payment_secret.clone()));
7694         // Claiming with all the correct values but the wrong secret should result in nothing...
7695         assert_eq!(nodes[2].node.claim_funds(payment_preimage, &None, 100_000), false);
7696         assert_eq!(nodes[2].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 100_000), false);
7697         // ...but with the right secret we should be able to claim all the way back
7698         claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage, Some(payment_secret.clone()), 100_000);
7699 }
7700
7701 #[test]
7702 fn test_simple_mpp() {
7703         // Simple test of sending a multi-path payment.
7704         let chanmon_cfgs = create_chanmon_cfgs(4);
7705         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7706         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
7707         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7708
7709         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7710         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7711         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7712         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7713         let logger = Arc::new(test_utils::TestLogger::new());
7714
7715         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
7716         let payment_secret = PaymentSecret([0xdb; 32]);
7717         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
7718         let mut route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[3].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, logger.clone()).unwrap();
7719         let path = route.paths[0].clone();
7720         route.paths.push(path);
7721         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
7722         route.paths[0][0].short_channel_id = chan_1_id;
7723         route.paths[0][1].short_channel_id = chan_3_id;
7724         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
7725         route.paths[1][0].short_channel_id = chan_2_id;
7726         route.paths[1][1].short_channel_id = chan_4_id;
7727         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, Some(payment_secret.clone()));
7728         // Claiming with all the correct values but the wrong secret should result in nothing...
7729         assert_eq!(nodes[3].node.claim_funds(payment_preimage, &None, 200_000), false);
7730         assert_eq!(nodes[3].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 200_000), false);
7731         // ...but with the right secret we should be able to claim all the way back
7732         claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage, Some(payment_secret), 200_000);
7733 }
7734
7735 #[test]
7736 fn test_update_err_monitor_lockdown() {
7737         // Our monitor will lock update of local commitment transaction if a broadcastion condition
7738         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
7739         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
7740         //
7741         // This scenario may happen in a watchtower setup, where watchtower process a block height
7742         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
7743         // commitment at same time.
7744
7745         let chanmon_cfgs = create_chanmon_cfgs(2);
7746         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7747         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7748         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7749
7750         // Create some initial channel
7751         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7752         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
7753
7754         // Rebalance the network to generate htlc in the two directions
7755         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
7756
7757         // Route a HTLC from node 0 to node 1 (but don't settle)
7758         let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
7759
7760         // Copy SimpleManyChannelMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
7761         let logger = Arc::new(test_utils::TestLogger::with_id(format!("node {}", 0)));
7762         let watchtower = {
7763                 let monitors = nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap();
7764                 let monitor = monitors.get(&outpoint).unwrap();
7765                 let mut w = test_utils::TestVecWriter(Vec::new());
7766                 monitor.write_for_disk(&mut w).unwrap();
7767                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
7768                                 &mut ::std::io::Cursor::new(&w.0), Arc::new(test_utils::TestLogger::new())).unwrap().1;
7769                 assert!(new_monitor == *monitor);
7770                 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, logger.clone() as Arc<Logger>));
7771                 let watchtower = test_utils::TestChannelMonitor::new(chain_monitor, &chanmon_cfgs[0].tx_broadcaster, logger.clone(), &chanmon_cfgs[0].fee_estimator);
7772                 assert!(watchtower.add_monitor(outpoint, new_monitor).is_ok());
7773                 watchtower
7774         };
7775         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7776         watchtower.simple_monitor.block_connected(&header, 200, &vec![], &vec![]);
7777
7778         // Try to update ChannelMonitor
7779         assert!(nodes[1].node.claim_funds(preimage, &None, 9_000_000));
7780         check_added_monitors!(nodes[1], 1);
7781         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7782         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
7783         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
7784         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
7785                 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator) {
7786                         if let Err(_) =  watchtower.simple_monitor.update_monitor(outpoint, update.clone()) {} else { assert!(false); }
7787                         if let Ok(_) = nodes[0].chan_monitor.update_monitor(outpoint, update) {} else { assert!(false); }
7788                 } else { assert!(false); }
7789         } else { assert!(false); };
7790         // Our local monitor is in-sync and hasn't processed yet timeout
7791         check_added_monitors!(nodes[0], 1);
7792         let events = nodes[0].node.get_and_clear_pending_events();
7793         assert_eq!(events.len(), 1);
7794 }