Merge pull request #620 from TheBlueMatt/2020-05-pre-bindings-cleanups
[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, Readable};
24 use util::config::UserConfig;
25
26 use bitcoin::util::hash::BitcoinHash;
27 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
28 use bitcoin::hash_types::{Txid, BlockHash};
29 use bitcoin::util::bip143;
30 use bitcoin::util::address::Address;
31 use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
32 use bitcoin::blockdata::block::{Block, BlockHeader};
33 use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType, OutPoint as BitcoinOutPoint};
34 use bitcoin::blockdata::script::{Builder, Script};
35 use bitcoin::blockdata::opcodes;
36 use bitcoin::blockdata::constants::genesis_block;
37 use bitcoin::network::constants::Network;
38
39 use bitcoin::hashes::sha256::Hash as Sha256;
40 use bitcoin::hashes::Hash;
41
42 use bitcoin::secp256k1::{Secp256k1, Message};
43 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
44
45 use std::collections::{BTreeSet, HashMap, HashSet};
46 use std::default::Default;
47 use std::sync::{Arc, Mutex};
48 use std::sync::atomic::Ordering;
49 use std::{mem, io};
50
51 use rand::{thread_rng, Rng};
52
53 use ln::functional_test_utils::*;
54
55 #[test]
56 fn test_insane_channel_opens() {
57         // Stand up a network of 2 nodes
58         let chanmon_cfgs = create_chanmon_cfgs(2);
59         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
60         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
61         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
62
63         // Instantiate channel parameters where we push the maximum msats given our
64         // funding satoshis
65         let channel_value_sat = 31337; // same as funding satoshis
66         let channel_reserve_satoshis = Channel::<EnforcingChannelKeys>::get_remote_channel_reserve_satoshis(channel_value_sat);
67         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
68
69         // Have node0 initiate a channel to node1 with aforementioned parameters
70         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
71
72         // Extract the channel open message from node0 to node1
73         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
74
75         // Test helper that asserts we get the correct error string given a mutator
76         // that supposedly makes the channel open message insane
77         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
78                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
79                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
80                 assert_eq!(msg_events.len(), 1);
81                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
82                         match action {
83                                 &ErrorAction::SendErrorMessage { .. } => {
84                                         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), expected_error_str.to_string(), 1);
85                                 },
86                                 _ => panic!("unexpected event!"),
87                         }
88                 } else { assert!(false); }
89         };
90
91         use ln::channel::MAX_FUNDING_SATOSHIS;
92         use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
93
94         // Test all mutations that would make the channel open message insane
95         insane_open_helper("funding value > 2^24", |mut msg| { msg.funding_satoshis = MAX_FUNDING_SATOSHIS; msg });
96
97         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
98
99         insane_open_helper("push_msat larger than funding value", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
100
101         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
102
103         insane_open_helper("Bogus; channel reserve is less than dust limit", |mut msg| { msg.dust_limit_satoshis = msg.channel_reserve_satoshis + 1; msg });
104
105         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 });
106
107         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 });
108
109         insane_open_helper("0 max_accpted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
110
111         insane_open_helper("max_accpted_htlcs > 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
112 }
113
114 #[test]
115 fn test_async_inbound_update_fee() {
116         let chanmon_cfgs = create_chanmon_cfgs(2);
117         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
118         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
119         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
120         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
121         let logger = test_utils::TestLogger::new();
122         let channel_id = chan.2;
123
124         // balancing
125         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
126
127         // A                                        B
128         // update_fee                            ->
129         // send (1) commitment_signed            -.
130         //                                       <- update_add_htlc/commitment_signed
131         // send (2) RAA (awaiting remote revoke) -.
132         // (1) commitment_signed is delivered    ->
133         //                                       .- send (3) RAA (awaiting remote revoke)
134         // (2) RAA is delivered                  ->
135         //                                       .- send (4) commitment_signed
136         //                                       <- (3) RAA is delivered
137         // send (5) commitment_signed            -.
138         //                                       <- (4) commitment_signed is delivered
139         // send (6) RAA                          -.
140         // (5) commitment_signed is delivered    ->
141         //                                       <- RAA
142         // (6) RAA is delivered                  ->
143
144         // First nodes[0] generates an update_fee
145         nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
146         check_added_monitors!(nodes[0], 1);
147
148         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
149         assert_eq!(events_0.len(), 1);
150         let (update_msg, commitment_signed) = match events_0[0] { // (1)
151                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
152                         (update_fee.as_ref(), commitment_signed)
153                 },
154                 _ => panic!("Unexpected event"),
155         };
156
157         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
158
159         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
160         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
161         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
162         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).unwrap(), our_payment_hash, &None).unwrap();
163         check_added_monitors!(nodes[1], 1);
164
165         let payment_event = {
166                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
167                 assert_eq!(events_1.len(), 1);
168                 SendEvent::from_event(events_1.remove(0))
169         };
170         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
171         assert_eq!(payment_event.msgs.len(), 1);
172
173         // ...now when the messages get delivered everyone should be happy
174         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
175         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
176         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
177         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
178         check_added_monitors!(nodes[0], 1);
179
180         // deliver(1), generate (3):
181         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
182         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
183         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
184         check_added_monitors!(nodes[1], 1);
185
186         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
187         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
188         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
189         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
190         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
191         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
192         assert!(bs_update.update_fee.is_none()); // (4)
193         check_added_monitors!(nodes[1], 1);
194
195         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
196         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
197         assert!(as_update.update_add_htlcs.is_empty()); // (5)
198         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
199         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
200         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
201         assert!(as_update.update_fee.is_none()); // (5)
202         check_added_monitors!(nodes[0], 1);
203
204         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
205         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
206         // only (6) so get_event_msg's assert(len == 1) passes
207         check_added_monitors!(nodes[0], 1);
208
209         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
210         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
211         check_added_monitors!(nodes[1], 1);
212
213         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
214         check_added_monitors!(nodes[0], 1);
215
216         let events_2 = nodes[0].node.get_and_clear_pending_events();
217         assert_eq!(events_2.len(), 1);
218         match events_2[0] {
219                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
220                 _ => panic!("Unexpected event"),
221         }
222
223         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
224         check_added_monitors!(nodes[1], 1);
225 }
226
227 #[test]
228 fn test_update_fee_unordered_raa() {
229         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
230         // crash in an earlier version of the update_fee patch)
231         let chanmon_cfgs = create_chanmon_cfgs(2);
232         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
233         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
234         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
235         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
236         let channel_id = chan.2;
237         let logger = test_utils::TestLogger::new();
238
239         // balancing
240         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
241
242         // First nodes[0] generates an update_fee
243         nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
244         check_added_monitors!(nodes[0], 1);
245
246         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
247         assert_eq!(events_0.len(), 1);
248         let update_msg = match events_0[0] { // (1)
249                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
250                         update_fee.as_ref()
251                 },
252                 _ => panic!("Unexpected event"),
253         };
254
255         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
256
257         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
258         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
259         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
260         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).unwrap(), our_payment_hash, &None).unwrap();
261         check_added_monitors!(nodes[1], 1);
262
263         let payment_event = {
264                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
265                 assert_eq!(events_1.len(), 1);
266                 SendEvent::from_event(events_1.remove(0))
267         };
268         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
269         assert_eq!(payment_event.msgs.len(), 1);
270
271         // ...now when the messages get delivered everyone should be happy
272         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
273         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
274         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
275         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
276         check_added_monitors!(nodes[0], 1);
277
278         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
279         check_added_monitors!(nodes[1], 1);
280
281         // We can't continue, sadly, because our (1) now has a bogus signature
282 }
283
284 #[test]
285 fn test_multi_flight_update_fee() {
286         let chanmon_cfgs = create_chanmon_cfgs(2);
287         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
288         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
289         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
290         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
291         let channel_id = chan.2;
292
293         // A                                        B
294         // update_fee/commitment_signed          ->
295         //                                       .- send (1) RAA and (2) commitment_signed
296         // update_fee (never committed)          ->
297         // (3) update_fee                        ->
298         // We have to manually generate the above update_fee, it is allowed by the protocol but we
299         // don't track which updates correspond to which revoke_and_ack responses so we're in
300         // AwaitingRAA mode and will not generate the update_fee yet.
301         //                                       <- (1) RAA delivered
302         // (3) is generated and send (4) CS      -.
303         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
304         // know the per_commitment_point to use for it.
305         //                                       <- (2) commitment_signed delivered
306         // revoke_and_ack                        ->
307         //                                          B should send no response here
308         // (4) commitment_signed delivered       ->
309         //                                       <- RAA/commitment_signed delivered
310         // revoke_and_ack                        ->
311
312         // First nodes[0] generates an update_fee
313         let initial_feerate = get_feerate!(nodes[0], channel_id);
314         nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
315         check_added_monitors!(nodes[0], 1);
316
317         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
318         assert_eq!(events_0.len(), 1);
319         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
320                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
321                         (update_fee.as_ref().unwrap(), commitment_signed)
322                 },
323                 _ => panic!("Unexpected event"),
324         };
325
326         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
327         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
328         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
329         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
330         check_added_monitors!(nodes[1], 1);
331
332         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
333         // transaction:
334         nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
335         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
336         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
337
338         // Create the (3) update_fee message that nodes[0] will generate before it does...
339         let mut update_msg_2 = msgs::UpdateFee {
340                 channel_id: update_msg_1.channel_id.clone(),
341                 feerate_per_kw: (initial_feerate + 30) as u32,
342         };
343
344         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
345
346         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
347         // Deliver (3)
348         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
349
350         // Deliver (1), generating (3) and (4)
351         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
352         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
353         check_added_monitors!(nodes[0], 1);
354         assert!(as_second_update.update_add_htlcs.is_empty());
355         assert!(as_second_update.update_fulfill_htlcs.is_empty());
356         assert!(as_second_update.update_fail_htlcs.is_empty());
357         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
358         // Check that the update_fee newly generated matches what we delivered:
359         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
360         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
361
362         // Deliver (2) commitment_signed
363         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
364         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
365         check_added_monitors!(nodes[0], 1);
366         // No commitment_signed so get_event_msg's assert(len == 1) passes
367
368         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
369         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
370         check_added_monitors!(nodes[1], 1);
371
372         // Delever (4)
373         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
374         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
375         check_added_monitors!(nodes[1], 1);
376
377         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
378         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
379         check_added_monitors!(nodes[0], 1);
380
381         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
382         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
383         // No commitment_signed so get_event_msg's assert(len == 1) passes
384         check_added_monitors!(nodes[0], 1);
385
386         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
387         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
388         check_added_monitors!(nodes[1], 1);
389 }
390
391 #[test]
392 fn test_1_conf_open() {
393         // Previously, if the minium_depth config was set to 1, we'd never send a funding_locked. This
394         // tests that we properly send one in that case.
395         let mut alice_config = UserConfig::default();
396         alice_config.own_channel_config.minimum_depth = 1;
397         alice_config.channel_options.announced_channel = true;
398         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
399         let mut bob_config = UserConfig::default();
400         bob_config.own_channel_config.minimum_depth = 1;
401         bob_config.channel_options.announced_channel = true;
402         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
403         let chanmon_cfgs = create_chanmon_cfgs(2);
404         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
405         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(alice_config), Some(bob_config)]);
406         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
407
408         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
409         assert!(nodes[0].chain_monitor.does_match_tx(&tx));
410         assert!(nodes[1].chain_monitor.does_match_tx(&tx));
411
412         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
413         nodes[1].block_notifier.block_connected_checked(&header, 1, &[&tx; 1], &[tx.version; 1]);
414         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()));
415
416         nodes[0].block_notifier.block_connected_checked(&header, 1, &[&tx; 1], &[tx.version; 1]);
417         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
418         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
419
420         for node in nodes {
421                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
422                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
423                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
424         }
425 }
426
427 fn do_test_sanity_on_in_flight_opens(steps: u8) {
428         // Previously, we had issues deserializing channels when we hadn't connected the first block
429         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
430         // serialization round-trips and simply do steps towards opening a channel and then drop the
431         // Node objects.
432
433         let chanmon_cfgs = create_chanmon_cfgs(2);
434         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
435         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
436         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
437
438         if steps & 0b1000_0000 != 0{
439                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
440                 nodes[0].block_notifier.block_connected_checked(&header, 1, &Vec::new(), &[0; 0]);
441                 nodes[1].block_notifier.block_connected_checked(&header, 1, &Vec::new(), &[0; 0]);
442         }
443
444         if steps & 0x0f == 0 { return; }
445         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
446         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
447
448         if steps & 0x0f == 1 { return; }
449         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
450         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
451
452         if steps & 0x0f == 2 { return; }
453         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
454
455         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
456
457         if steps & 0x0f == 3 { return; }
458         nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
459         check_added_monitors!(nodes[0], 0);
460         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
461
462         if steps & 0x0f == 4 { return; }
463         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
464         {
465                 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
466                 assert_eq!(added_monitors.len(), 1);
467                 assert_eq!(added_monitors[0].0, funding_output);
468                 added_monitors.clear();
469         }
470         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
471
472         if steps & 0x0f == 5 { return; }
473         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
474         {
475                 let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
476                 assert_eq!(added_monitors.len(), 1);
477                 assert_eq!(added_monitors[0].0, funding_output);
478                 added_monitors.clear();
479         }
480
481         let events_4 = nodes[0].node.get_and_clear_pending_events();
482         assert_eq!(events_4.len(), 1);
483         match events_4[0] {
484                 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
485                         assert_eq!(user_channel_id, 42);
486                         assert_eq!(*funding_txo, funding_output);
487                 },
488                 _ => panic!("Unexpected event"),
489         };
490
491         if steps & 0x0f == 6 { return; }
492         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx);
493
494         if steps & 0x0f == 7 { return; }
495         confirm_transaction(&nodes[0].block_notifier, &nodes[0].chain_monitor, &tx, tx.version);
496         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
497 }
498
499 #[test]
500 fn test_sanity_on_in_flight_opens() {
501         do_test_sanity_on_in_flight_opens(0);
502         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
503         do_test_sanity_on_in_flight_opens(1);
504         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
505         do_test_sanity_on_in_flight_opens(2);
506         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
507         do_test_sanity_on_in_flight_opens(3);
508         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
509         do_test_sanity_on_in_flight_opens(4);
510         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
511         do_test_sanity_on_in_flight_opens(5);
512         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
513         do_test_sanity_on_in_flight_opens(6);
514         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
515         do_test_sanity_on_in_flight_opens(7);
516         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
517         do_test_sanity_on_in_flight_opens(8);
518         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
519 }
520
521 #[test]
522 fn test_update_fee_vanilla() {
523         let chanmon_cfgs = create_chanmon_cfgs(2);
524         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
525         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
526         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
527         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
528         let channel_id = chan.2;
529
530         let feerate = get_feerate!(nodes[0], channel_id);
531         nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
532         check_added_monitors!(nodes[0], 1);
533
534         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
535         assert_eq!(events_0.len(), 1);
536         let (update_msg, commitment_signed) = match events_0[0] {
537                         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 } } => {
538                         (update_fee.as_ref(), commitment_signed)
539                 },
540                 _ => panic!("Unexpected event"),
541         };
542         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
543
544         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
545         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
546         check_added_monitors!(nodes[1], 1);
547
548         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
549         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
550         check_added_monitors!(nodes[0], 1);
551
552         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
553         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
554         // No commitment_signed so get_event_msg's assert(len == 1) passes
555         check_added_monitors!(nodes[0], 1);
556
557         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
558         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
559         check_added_monitors!(nodes[1], 1);
560 }
561
562 #[test]
563 fn test_update_fee_that_funder_cannot_afford() {
564         let chanmon_cfgs = create_chanmon_cfgs(2);
565         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
566         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
567         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
568         let channel_value = 1888;
569         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000, InitFeatures::known(), InitFeatures::known());
570         let channel_id = chan.2;
571
572         let feerate = 260;
573         nodes[0].node.update_fee(channel_id, feerate).unwrap();
574         check_added_monitors!(nodes[0], 1);
575         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
576
577         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
578
579         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
580
581         //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
582         //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
583         {
584                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
585
586                 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
587                 let num_htlcs = commitment_tx.output.len() - 2;
588                 let total_fee: u64 = feerate * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
589                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
590                 actual_fee = channel_value - actual_fee;
591                 assert_eq!(total_fee, actual_fee);
592         }
593
594         //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
595         //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
596         nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
597         check_added_monitors!(nodes[0], 1);
598
599         let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
600
601         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap());
602
603         //While producing the commitment_signed response after handling a received update_fee request the
604         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
605         //Should produce and error.
606         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed);
607         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
608         check_added_monitors!(nodes[1], 1);
609         check_closed_broadcast!(nodes[1], true);
610 }
611
612 #[test]
613 fn test_update_fee_with_fundee_update_add_htlc() {
614         let chanmon_cfgs = create_chanmon_cfgs(2);
615         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
616         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
617         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
618         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
619         let channel_id = chan.2;
620         let logger = test_utils::TestLogger::new();
621
622         // balancing
623         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
624
625         let feerate = get_feerate!(nodes[0], channel_id);
626         nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
627         check_added_monitors!(nodes[0], 1);
628
629         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
630         assert_eq!(events_0.len(), 1);
631         let (update_msg, commitment_signed) = match events_0[0] {
632                         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 } } => {
633                         (update_fee.as_ref(), commitment_signed)
634                 },
635                 _ => panic!("Unexpected event"),
636         };
637         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
638         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
639         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
640         check_added_monitors!(nodes[1], 1);
641
642         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
643         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
644         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).unwrap();
645
646         // nothing happens since node[1] is in AwaitingRemoteRevoke
647         nodes[1].node.send_payment(&route, our_payment_hash, &None).unwrap();
648         {
649                 let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
650                 assert_eq!(added_monitors.len(), 0);
651                 added_monitors.clear();
652         }
653         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
654         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
655         // node[1] has nothing to do
656
657         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
658         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
659         check_added_monitors!(nodes[0], 1);
660
661         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
662         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
663         // No commitment_signed so get_event_msg's assert(len == 1) passes
664         check_added_monitors!(nodes[0], 1);
665         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
666         check_added_monitors!(nodes[1], 1);
667         // AwaitingRemoteRevoke ends here
668
669         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
670         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
671         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
672         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
673         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
674         assert_eq!(commitment_update.update_fee.is_none(), true);
675
676         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
677         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
678         check_added_monitors!(nodes[0], 1);
679         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
680
681         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
682         check_added_monitors!(nodes[1], 1);
683         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
684
685         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
686         check_added_monitors!(nodes[1], 1);
687         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
688         // No commitment_signed so get_event_msg's assert(len == 1) passes
689
690         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
691         check_added_monitors!(nodes[0], 1);
692         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
693
694         expect_pending_htlcs_forwardable!(nodes[0]);
695
696         let events = nodes[0].node.get_and_clear_pending_events();
697         assert_eq!(events.len(), 1);
698         match events[0] {
699                 Event::PaymentReceived { .. } => { },
700                 _ => panic!("Unexpected event"),
701         };
702
703         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage, 800_000);
704
705         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000, 800_000);
706         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000, 800_000);
707         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
708 }
709
710 #[test]
711 fn test_update_fee() {
712         let chanmon_cfgs = create_chanmon_cfgs(2);
713         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
714         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
715         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
716         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
717         let channel_id = chan.2;
718
719         // A                                        B
720         // (1) update_fee/commitment_signed      ->
721         //                                       <- (2) revoke_and_ack
722         //                                       .- send (3) commitment_signed
723         // (4) update_fee/commitment_signed      ->
724         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
725         //                                       <- (3) commitment_signed delivered
726         // send (6) revoke_and_ack               -.
727         //                                       <- (5) deliver revoke_and_ack
728         // (6) deliver revoke_and_ack            ->
729         //                                       .- send (7) commitment_signed in response to (4)
730         //                                       <- (7) deliver commitment_signed
731         // revoke_and_ack                        ->
732
733         // Create and deliver (1)...
734         let feerate = get_feerate!(nodes[0], channel_id);
735         nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
736         check_added_monitors!(nodes[0], 1);
737
738         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
739         assert_eq!(events_0.len(), 1);
740         let (update_msg, commitment_signed) = match events_0[0] {
741                         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 } } => {
742                         (update_fee.as_ref(), commitment_signed)
743                 },
744                 _ => panic!("Unexpected event"),
745         };
746         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
747
748         // Generate (2) and (3):
749         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
750         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
751         check_added_monitors!(nodes[1], 1);
752
753         // Deliver (2):
754         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
755         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
756         check_added_monitors!(nodes[0], 1);
757
758         // Create and deliver (4)...
759         nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
760         check_added_monitors!(nodes[0], 1);
761         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
762         assert_eq!(events_0.len(), 1);
763         let (update_msg, commitment_signed) = match events_0[0] {
764                         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 } } => {
765                         (update_fee.as_ref(), commitment_signed)
766                 },
767                 _ => panic!("Unexpected event"),
768         };
769
770         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
771         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
772         check_added_monitors!(nodes[1], 1);
773         // ... creating (5)
774         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
775         // No commitment_signed so get_event_msg's assert(len == 1) passes
776
777         // Handle (3), creating (6):
778         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
779         check_added_monitors!(nodes[0], 1);
780         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
781         // No commitment_signed so get_event_msg's assert(len == 1) passes
782
783         // Deliver (5):
784         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
785         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
786         check_added_monitors!(nodes[0], 1);
787
788         // Deliver (6), creating (7):
789         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
790         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
791         assert!(commitment_update.update_add_htlcs.is_empty());
792         assert!(commitment_update.update_fulfill_htlcs.is_empty());
793         assert!(commitment_update.update_fail_htlcs.is_empty());
794         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
795         assert!(commitment_update.update_fee.is_none());
796         check_added_monitors!(nodes[1], 1);
797
798         // Deliver (7)
799         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
800         check_added_monitors!(nodes[0], 1);
801         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
802         // No commitment_signed so get_event_msg's assert(len == 1) passes
803
804         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
805         check_added_monitors!(nodes[1], 1);
806         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
807
808         assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
809         assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
810         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
811 }
812
813 #[test]
814 fn pre_funding_lock_shutdown_test() {
815         // Test sending a shutdown prior to funding_locked after funding generation
816         let chanmon_cfgs = create_chanmon_cfgs(2);
817         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
818         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
819         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
820         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0, InitFeatures::known(), InitFeatures::known());
821         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
822         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![tx.clone()]}, 1);
823         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![tx.clone()]}, 1);
824
825         nodes[0].node.close_channel(&OutPoint { txid: tx.txid(), index: 0 }.to_channel_id()).unwrap();
826         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
827         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
828         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
829         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
830
831         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
832         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
833         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
834         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
835         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
836         assert!(node_0_none.is_none());
837
838         assert!(nodes[0].node.list_channels().is_empty());
839         assert!(nodes[1].node.list_channels().is_empty());
840 }
841
842 #[test]
843 fn updates_shutdown_wait() {
844         // Test sending a shutdown with outstanding updates pending
845         let chanmon_cfgs = create_chanmon_cfgs(3);
846         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
847         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
848         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
849         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
850         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
851         let logger = test_utils::TestLogger::new();
852
853         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
854
855         nodes[0].node.close_channel(&chan_1.2).unwrap();
856         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
857         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
858         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
859         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
860
861         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
862         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
863
864         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
865
866         let net_graph_msg_handler0 = &nodes[0].net_graph_msg_handler;
867         let net_graph_msg_handler1 = &nodes[1].net_graph_msg_handler;
868         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).unwrap();
869         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).unwrap();
870         unwrap_send_err!(nodes[0].node.send_payment(&route_1, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
871         unwrap_send_err!(nodes[1].node.send_payment(&route_2, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
872
873         assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
874         check_added_monitors!(nodes[2], 1);
875         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
876         assert!(updates.update_add_htlcs.is_empty());
877         assert!(updates.update_fail_htlcs.is_empty());
878         assert!(updates.update_fail_malformed_htlcs.is_empty());
879         assert!(updates.update_fee.is_none());
880         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
881         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
882         check_added_monitors!(nodes[1], 1);
883         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
884         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
885
886         assert!(updates_2.update_add_htlcs.is_empty());
887         assert!(updates_2.update_fail_htlcs.is_empty());
888         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
889         assert!(updates_2.update_fee.is_none());
890         assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
891         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
892         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
893
894         let events = nodes[0].node.get_and_clear_pending_events();
895         assert_eq!(events.len(), 1);
896         match events[0] {
897                 Event::PaymentSent { ref payment_preimage } => {
898                         assert_eq!(our_payment_preimage, *payment_preimage);
899                 },
900                 _ => panic!("Unexpected event"),
901         }
902
903         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
904         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
905         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
906         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
907         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
908         assert!(node_0_none.is_none());
909
910         assert!(nodes[0].node.list_channels().is_empty());
911
912         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
913         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
914         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
915         assert!(nodes[1].node.list_channels().is_empty());
916         assert!(nodes[2].node.list_channels().is_empty());
917 }
918
919 #[test]
920 fn htlc_fail_async_shutdown() {
921         // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
922         let chanmon_cfgs = create_chanmon_cfgs(3);
923         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
924         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
925         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
926         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
927         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
928         let logger = test_utils::TestLogger::new();
929
930         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
931         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
932         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).unwrap();
933         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
934         check_added_monitors!(nodes[0], 1);
935         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
936         assert_eq!(updates.update_add_htlcs.len(), 1);
937         assert!(updates.update_fulfill_htlcs.is_empty());
938         assert!(updates.update_fail_htlcs.is_empty());
939         assert!(updates.update_fail_malformed_htlcs.is_empty());
940         assert!(updates.update_fee.is_none());
941
942         nodes[1].node.close_channel(&chan_1.2).unwrap();
943         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
944         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
945         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
946
947         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
948         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
949         check_added_monitors!(nodes[1], 1);
950         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
951         commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
952
953         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
954         assert!(updates_2.update_add_htlcs.is_empty());
955         assert!(updates_2.update_fulfill_htlcs.is_empty());
956         assert_eq!(updates_2.update_fail_htlcs.len(), 1);
957         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
958         assert!(updates_2.update_fee.is_none());
959
960         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]);
961         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
962
963         expect_payment_failed!(nodes[0], our_payment_hash, false);
964
965         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
966         assert_eq!(msg_events.len(), 2);
967         let node_0_closing_signed = match msg_events[0] {
968                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
969                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
970                         (*msg).clone()
971                 },
972                 _ => panic!("Unexpected event"),
973         };
974         match msg_events[1] {
975                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
976                         assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
977                 },
978                 _ => panic!("Unexpected event"),
979         }
980
981         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
982         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
983         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
984         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
985         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
986         assert!(node_0_none.is_none());
987
988         assert!(nodes[0].node.list_channels().is_empty());
989
990         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
991         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
992         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
993         assert!(nodes[1].node.list_channels().is_empty());
994         assert!(nodes[2].node.list_channels().is_empty());
995 }
996
997 fn do_test_shutdown_rebroadcast(recv_count: u8) {
998         // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
999         // messages delivered prior to disconnect
1000         let chanmon_cfgs = create_chanmon_cfgs(3);
1001         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1002         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1003         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1004         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1005         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1006
1007         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
1008
1009         nodes[1].node.close_channel(&chan_1.2).unwrap();
1010         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1011         if recv_count > 0 {
1012                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
1013                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1014                 if recv_count > 1 {
1015                         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
1016                 }
1017         }
1018
1019         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1020         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1021
1022         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1023         let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1024         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1025         let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1026
1027         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish);
1028         let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1029         assert!(node_1_shutdown == node_1_2nd_shutdown);
1030
1031         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish);
1032         let node_0_2nd_shutdown = if recv_count > 0 {
1033                 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1034                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
1035                 node_0_2nd_shutdown
1036         } else {
1037                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1038                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
1039                 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
1040         };
1041         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown);
1042
1043         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1044         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1045
1046         assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
1047         check_added_monitors!(nodes[2], 1);
1048         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1049         assert!(updates.update_add_htlcs.is_empty());
1050         assert!(updates.update_fail_htlcs.is_empty());
1051         assert!(updates.update_fail_malformed_htlcs.is_empty());
1052         assert!(updates.update_fee.is_none());
1053         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
1054         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
1055         check_added_monitors!(nodes[1], 1);
1056         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1057         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
1058
1059         assert!(updates_2.update_add_htlcs.is_empty());
1060         assert!(updates_2.update_fail_htlcs.is_empty());
1061         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
1062         assert!(updates_2.update_fee.is_none());
1063         assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
1064         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
1065         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
1066
1067         let events = nodes[0].node.get_and_clear_pending_events();
1068         assert_eq!(events.len(), 1);
1069         match events[0] {
1070                 Event::PaymentSent { ref payment_preimage } => {
1071                         assert_eq!(our_payment_preimage, *payment_preimage);
1072                 },
1073                 _ => panic!("Unexpected event"),
1074         }
1075
1076         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1077         if recv_count > 0 {
1078                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
1079                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1080                 assert!(node_1_closing_signed.is_some());
1081         }
1082
1083         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1084         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1085
1086         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1087         let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1088         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1089         if recv_count == 0 {
1090                 // If all closing_signeds weren't delivered we can just resume where we left off...
1091                 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1092
1093                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish);
1094                 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1095                 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
1096
1097                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1098                 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1099                 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
1100
1101                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown);
1102                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1103
1104                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown);
1105                 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1106                 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
1107
1108                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed);
1109                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1110                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
1111                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1112                 assert!(node_0_none.is_none());
1113         } else {
1114                 // If one node, however, received + responded with an identical closing_signed we end
1115                 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
1116                 // There isn't really anything better we can do simply, but in the future we might
1117                 // explore storing a set of recently-closed channels that got disconnected during
1118                 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
1119                 // give our counterparty enough time to (potentially) broadcast a cooperative closing
1120                 // transaction.
1121                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1122
1123                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1124                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1125                 assert_eq!(msg_events.len(), 1);
1126                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
1127                         match action {
1128                                 &ErrorAction::SendErrorMessage { ref msg } => {
1129                                         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
1130                                         assert_eq!(msg.channel_id, chan_1.2);
1131                                 },
1132                                 _ => panic!("Unexpected event!"),
1133                         }
1134                 } else { panic!("Needed SendErrorMessage close"); }
1135
1136                 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
1137                 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
1138                 // closing_signed so we do it ourselves
1139                 check_closed_broadcast!(nodes[0], false);
1140                 check_added_monitors!(nodes[0], 1);
1141         }
1142
1143         assert!(nodes[0].node.list_channels().is_empty());
1144
1145         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1146         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1147         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1148         assert!(nodes[1].node.list_channels().is_empty());
1149         assert!(nodes[2].node.list_channels().is_empty());
1150 }
1151
1152 #[test]
1153 fn test_shutdown_rebroadcast() {
1154         do_test_shutdown_rebroadcast(0);
1155         do_test_shutdown_rebroadcast(1);
1156         do_test_shutdown_rebroadcast(2);
1157 }
1158
1159 #[test]
1160 fn fake_network_test() {
1161         // Simple test which builds a network of ChannelManagers, connects them to each other, and
1162         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
1163         let chanmon_cfgs = create_chanmon_cfgs(4);
1164         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1165         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1166         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1167
1168         // Create some initial channels
1169         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1170         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1171         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1172
1173         // Rebalance the network a bit by relaying one payment through all the channels...
1174         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
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
1179         // Send some more payments
1180         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000, 1_000_000);
1181         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000, 1_000_000);
1182         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000, 1_000_000);
1183
1184         // Test failure packets
1185         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1186         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1187
1188         // Add a new channel that skips 3
1189         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1190
1191         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000, 1_000_000);
1192         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000, 1_000_000);
1193         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_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
1199         // Do some rebalance loop payments, simultaneously
1200         let mut hops = Vec::with_capacity(3);
1201         hops.push(RouteHop {
1202                 pubkey: nodes[2].node.get_our_node_id(),
1203                 node_features: NodeFeatures::empty(),
1204                 short_channel_id: chan_2.0.contents.short_channel_id,
1205                 channel_features: ChannelFeatures::empty(),
1206                 fee_msat: 0,
1207                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1208         });
1209         hops.push(RouteHop {
1210                 pubkey: nodes[3].node.get_our_node_id(),
1211                 node_features: NodeFeatures::empty(),
1212                 short_channel_id: chan_3.0.contents.short_channel_id,
1213                 channel_features: ChannelFeatures::empty(),
1214                 fee_msat: 0,
1215                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1216         });
1217         hops.push(RouteHop {
1218                 pubkey: nodes[1].node.get_our_node_id(),
1219                 node_features: NodeFeatures::empty(),
1220                 short_channel_id: chan_4.0.contents.short_channel_id,
1221                 channel_features: ChannelFeatures::empty(),
1222                 fee_msat: 1000000,
1223                 cltv_expiry_delta: TEST_FINAL_CLTV,
1224         });
1225         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;
1226         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;
1227         let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1228
1229         let mut hops = Vec::with_capacity(3);
1230         hops.push(RouteHop {
1231                 pubkey: nodes[3].node.get_our_node_id(),
1232                 node_features: NodeFeatures::empty(),
1233                 short_channel_id: chan_4.0.contents.short_channel_id,
1234                 channel_features: ChannelFeatures::empty(),
1235                 fee_msat: 0,
1236                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1237         });
1238         hops.push(RouteHop {
1239                 pubkey: nodes[2].node.get_our_node_id(),
1240                 node_features: NodeFeatures::empty(),
1241                 short_channel_id: chan_3.0.contents.short_channel_id,
1242                 channel_features: ChannelFeatures::empty(),
1243                 fee_msat: 0,
1244                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1245         });
1246         hops.push(RouteHop {
1247                 pubkey: nodes[1].node.get_our_node_id(),
1248                 node_features: NodeFeatures::empty(),
1249                 short_channel_id: chan_2.0.contents.short_channel_id,
1250                 channel_features: ChannelFeatures::empty(),
1251                 fee_msat: 1000000,
1252                 cltv_expiry_delta: TEST_FINAL_CLTV,
1253         });
1254         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;
1255         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;
1256         let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1257
1258         // Claim the rebalances...
1259         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1260         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1, 1_000_000);
1261
1262         // Add a duplicate new channel from 2 to 4
1263         let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1264
1265         // Send some payments across both channels
1266         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1267         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1268         let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1269
1270
1271         route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1272         let events = nodes[0].node.get_and_clear_pending_msg_events();
1273         assert_eq!(events.len(), 0);
1274         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);
1275
1276         //TODO: Test that routes work again here as we've been notified that the channel is full
1277
1278         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3, 3_000_000);
1279         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4, 3_000_000);
1280         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5, 3_000_000);
1281
1282         // Close down the channels...
1283         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1284         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1285         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1286         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1287         close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1288 }
1289
1290 #[test]
1291 fn holding_cell_htlc_counting() {
1292         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1293         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1294         // commitment dance rounds.
1295         let chanmon_cfgs = create_chanmon_cfgs(3);
1296         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1297         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1298         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1299         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1300         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1301         let logger = test_utils::TestLogger::new();
1302
1303         let mut payments = Vec::new();
1304         for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1305                 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1306                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1307                 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).unwrap();
1308                 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
1309                 payments.push((payment_preimage, payment_hash));
1310         }
1311         check_added_monitors!(nodes[1], 1);
1312
1313         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1314         assert_eq!(events.len(), 1);
1315         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1316         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1317
1318         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1319         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1320         // another HTLC.
1321         let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
1322         {
1323                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1324                 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).unwrap();
1325                 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &None), true, APIError::ChannelUnavailable { err },
1326                         assert_eq!(err, "Cannot push more than their max accepted HTLCs"));
1327                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1328                 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1329         }
1330
1331         // This should also be true if we try to forward a payment.
1332         let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
1333         {
1334                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1335                 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).unwrap();
1336                 nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
1337                 check_added_monitors!(nodes[0], 1);
1338         }
1339
1340         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1341         assert_eq!(events.len(), 1);
1342         let payment_event = SendEvent::from_event(events.pop().unwrap());
1343         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1344
1345         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1346         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1347         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1348         // fails), the second will process the resulting failure and fail the HTLC backward.
1349         expect_pending_htlcs_forwardable!(nodes[1]);
1350         expect_pending_htlcs_forwardable!(nodes[1]);
1351         check_added_monitors!(nodes[1], 1);
1352
1353         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1354         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1355         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1356
1357         let events = nodes[0].node.get_and_clear_pending_msg_events();
1358         assert_eq!(events.len(), 1);
1359         match events[0] {
1360                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
1361                         assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
1362                 },
1363                 _ => panic!("Unexpected event"),
1364         }
1365
1366         expect_payment_failed!(nodes[0], payment_hash_2, false);
1367
1368         // Now forward all the pending HTLCs and claim them back
1369         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1370         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1371         check_added_monitors!(nodes[2], 1);
1372
1373         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1374         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1375         check_added_monitors!(nodes[1], 1);
1376         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1377
1378         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1379         check_added_monitors!(nodes[1], 1);
1380         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1381
1382         for ref update in as_updates.update_add_htlcs.iter() {
1383                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1384         }
1385         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1386         check_added_monitors!(nodes[2], 1);
1387         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1388         check_added_monitors!(nodes[2], 1);
1389         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1390
1391         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1392         check_added_monitors!(nodes[1], 1);
1393         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1394         check_added_monitors!(nodes[1], 1);
1395         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1396
1397         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1398         check_added_monitors!(nodes[2], 1);
1399
1400         expect_pending_htlcs_forwardable!(nodes[2]);
1401
1402         let events = nodes[2].node.get_and_clear_pending_events();
1403         assert_eq!(events.len(), payments.len());
1404         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1405                 match event {
1406                         &Event::PaymentReceived { ref payment_hash, .. } => {
1407                                 assert_eq!(*payment_hash, *hash);
1408                         },
1409                         _ => panic!("Unexpected event"),
1410                 };
1411         }
1412
1413         for (preimage, _) in payments.drain(..) {
1414                 claim_payment(&nodes[1], &[&nodes[2]], preimage, 100_000);
1415         }
1416
1417         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000, 1_000_000);
1418 }
1419
1420 #[test]
1421 fn duplicate_htlc_test() {
1422         // Test that we accept duplicate payment_hash HTLCs across the network and that
1423         // claiming/failing them are all separate and don't affect each other
1424         let chanmon_cfgs = create_chanmon_cfgs(6);
1425         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1426         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1427         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1428
1429         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1430         create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1431         create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1432         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1433         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1434         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1435
1436         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1437
1438         *nodes[0].network_payment_count.borrow_mut() -= 1;
1439         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1440
1441         *nodes[0].network_payment_count.borrow_mut() -= 1;
1442         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1443
1444         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage, 1_000_000);
1445         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1446         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage, 1_000_000);
1447 }
1448
1449 #[test]
1450 fn test_duplicate_htlc_different_direction_onchain() {
1451         // Test that ChannelMonitor doesn't generate 2 preimage txn
1452         // when we have 2 HTLCs with same preimage that go across a node
1453         // in opposite directions.
1454         let chanmon_cfgs = create_chanmon_cfgs(2);
1455         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1456         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1457         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1458
1459         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1460         let logger = test_utils::TestLogger::new();
1461
1462         // balancing
1463         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
1464
1465         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1466
1467         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1468         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).unwrap();
1469         send_along_route_with_hash(&nodes[1], route, &vec!(&nodes[0])[..], 800_000, payment_hash);
1470
1471         // Provide preimage to node 0 by claiming payment
1472         nodes[0].node.claim_funds(payment_preimage, &None, 800_000);
1473         check_added_monitors!(nodes[0], 1);
1474
1475         // Broadcast node 1 commitment txn
1476         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1477
1478         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1479         let mut has_both_htlcs = 0; // check htlcs match ones committed
1480         for outp in remote_txn[0].output.iter() {
1481                 if outp.value == 800_000 / 1000 {
1482                         has_both_htlcs += 1;
1483                 } else if outp.value == 900_000 / 1000 {
1484                         has_both_htlcs += 1;
1485                 }
1486         }
1487         assert_eq!(has_both_htlcs, 2);
1488
1489         let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1490         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
1491         check_added_monitors!(nodes[0], 1);
1492
1493         // Check we only broadcast 1 timeout tx
1494         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1495         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()) };
1496         assert_eq!(claim_txn.len(), 5);
1497         check_spends!(claim_txn[2], chan_1.3);
1498         check_spends!(claim_txn[3], claim_txn[2]);
1499         assert_eq!(htlc_pair.0.input.len(), 1);
1500         assert_eq!(htlc_pair.0.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1501         check_spends!(htlc_pair.0, remote_txn[0]);
1502         assert_eq!(htlc_pair.1.input.len(), 1);
1503         assert_eq!(htlc_pair.1.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1504         check_spends!(htlc_pair.1, remote_txn[0]);
1505
1506         let events = nodes[0].node.get_and_clear_pending_msg_events();
1507         assert_eq!(events.len(), 2);
1508         for e in events {
1509                 match e {
1510                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1511                         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, .. } } => {
1512                                 assert!(update_add_htlcs.is_empty());
1513                                 assert!(update_fail_htlcs.is_empty());
1514                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1515                                 assert!(update_fail_malformed_htlcs.is_empty());
1516                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1517                         },
1518                         _ => panic!("Unexpected event"),
1519                 }
1520         }
1521 }
1522
1523 fn do_channel_reserve_test(test_recv: bool) {
1524
1525         let chanmon_cfgs = create_chanmon_cfgs(3);
1526         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1527         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1528         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1529         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1900, 1001, InitFeatures::known(), InitFeatures::known());
1530         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1900, 1001, InitFeatures::known(), InitFeatures::known());
1531         let logger = test_utils::TestLogger::new();
1532
1533         let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1534         let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1535
1536         let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1537         let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1538
1539         macro_rules! get_route_and_payment_hash {
1540                 ($recv_value: expr) => {{
1541                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1542                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1543                         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).unwrap();
1544                         (route, payment_hash, payment_preimage)
1545                 }}
1546         };
1547
1548         macro_rules! expect_forward {
1549                 ($node: expr) => {{
1550                         let mut events = $node.node.get_and_clear_pending_msg_events();
1551                         assert_eq!(events.len(), 1);
1552                         check_added_monitors!($node, 1);
1553                         let payment_event = SendEvent::from_event(events.remove(0));
1554                         payment_event
1555                 }}
1556         }
1557
1558         let feemsat = 239; // somehow we know?
1559         let total_fee_msat = (nodes.len() - 2) as u64 * 239;
1560
1561         let recv_value_0 = stat01.their_max_htlc_value_in_flight_msat - total_fee_msat;
1562
1563         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1564         {
1565                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
1566                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1567                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
1568                         assert_eq!(err, "Cannot send value that would put us over the max HTLC value in flight our peer will accept"));
1569                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1570                 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);
1571         }
1572
1573         let mut htlc_id = 0;
1574         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1575         // nodes[0]'s wealth
1576         loop {
1577                 let amt_msat = recv_value_0 + total_fee_msat;
1578                 if stat01.value_to_self_msat - amt_msat < stat01.channel_reserve_msat {
1579                         break;
1580                 }
1581                 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0, recv_value_0);
1582                 htlc_id += 1;
1583
1584                 let (stat01_, stat11_, stat12_, stat22_) = (
1585                         get_channel_value_stat!(nodes[0], chan_1.2),
1586                         get_channel_value_stat!(nodes[1], chan_1.2),
1587                         get_channel_value_stat!(nodes[1], chan_2.2),
1588                         get_channel_value_stat!(nodes[2], chan_2.2),
1589                 );
1590
1591                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1592                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1593                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1594                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1595                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1596         }
1597
1598         {
1599                 let recv_value = stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat;
1600                 // attempt to get channel_reserve violation
1601                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value + 1);
1602                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
1603                         assert_eq!(err, "Cannot send value that would put us under local channel reserve value"));
1604                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1605                 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);
1606         }
1607
1608         // adding pending output
1609         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat)/2;
1610         let amt_msat_1 = recv_value_1 + total_fee_msat;
1611
1612         let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
1613         let payment_event_1 = {
1614                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
1615                 check_added_monitors!(nodes[0], 1);
1616
1617                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1618                 assert_eq!(events.len(), 1);
1619                 SendEvent::from_event(events.remove(0))
1620         };
1621         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1622
1623         // channel reserve test with htlc pending output > 0
1624         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat;
1625         {
1626                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
1627                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
1628                         assert_eq!(err, "Cannot send value that would put us under local channel reserve value"));
1629                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1630                 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);
1631         }
1632
1633         {
1634                 // test channel_reserve test on nodes[1] side
1635                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
1636
1637                 // Need to manually create update_add_htlc message to go around the channel reserve check in send_htlc()
1638                 let secp_ctx = Secp256k1::new();
1639                 let session_priv = SecretKey::from_slice(&{
1640                         let mut session_key = [0; 32];
1641                         let mut rng = thread_rng();
1642                         rng.fill_bytes(&mut session_key);
1643                         session_key
1644                 }).expect("RNG is bad!");
1645
1646                 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1647                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1648                 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], recv_value_2 + 1, &None, cur_height).unwrap();
1649                 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
1650                 let msg = msgs::UpdateAddHTLC {
1651                         channel_id: chan_1.2,
1652                         htlc_id,
1653                         amount_msat: htlc_msat,
1654                         payment_hash: our_payment_hash,
1655                         cltv_expiry: htlc_cltv,
1656                         onion_routing_packet: onion_packet,
1657                 };
1658
1659                 if test_recv {
1660                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1661                         // If we send a garbage message, the channel should get closed, making the rest of this test case fail.
1662                         assert_eq!(nodes[1].node.list_channels().len(), 1);
1663                         assert_eq!(nodes[1].node.list_channels().len(), 1);
1664                         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1665                         assert_eq!(err_msg.data, "Remote HTLC add would put them under their reserve value");
1666                         check_added_monitors!(nodes[1], 1);
1667                         return;
1668                 }
1669         }
1670
1671         // split the rest to test holding cell
1672         let recv_value_21 = recv_value_2/2;
1673         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat;
1674         {
1675                 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1676                 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);
1677         }
1678
1679         // now see if they go through on both sides
1680         let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
1681         // but this will stuck in the holding cell
1682         nodes[0].node.send_payment(&route_21, our_payment_hash_21, &None).unwrap();
1683         check_added_monitors!(nodes[0], 0);
1684         let events = nodes[0].node.get_and_clear_pending_events();
1685         assert_eq!(events.len(), 0);
1686
1687         // test with outbound holding cell amount > 0
1688         {
1689                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
1690                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
1691                         assert_eq!(err, "Cannot send value that would put us under local channel reserve value"));
1692                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1693                 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);
1694         }
1695
1696         let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
1697         // this will also stuck in the holding cell
1698         nodes[0].node.send_payment(&route_22, our_payment_hash_22, &None).unwrap();
1699         check_added_monitors!(nodes[0], 0);
1700         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1701         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1702
1703         // flush the pending htlc
1704         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1705         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1706         check_added_monitors!(nodes[1], 1);
1707
1708         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1709         check_added_monitors!(nodes[0], 1);
1710         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1711
1712         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1713         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1714         // No commitment_signed so get_event_msg's assert(len == 1) passes
1715         check_added_monitors!(nodes[0], 1);
1716
1717         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1718         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1719         check_added_monitors!(nodes[1], 1);
1720
1721         expect_pending_htlcs_forwardable!(nodes[1]);
1722
1723         let ref payment_event_11 = expect_forward!(nodes[1]);
1724         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1725         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1726
1727         expect_pending_htlcs_forwardable!(nodes[2]);
1728         expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
1729
1730         // flush the htlcs in the holding cell
1731         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1732         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1733         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1734         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1735         expect_pending_htlcs_forwardable!(nodes[1]);
1736
1737         let ref payment_event_3 = expect_forward!(nodes[1]);
1738         assert_eq!(payment_event_3.msgs.len(), 2);
1739         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1740         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1741
1742         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1743         expect_pending_htlcs_forwardable!(nodes[2]);
1744
1745         let events = nodes[2].node.get_and_clear_pending_events();
1746         assert_eq!(events.len(), 2);
1747         match events[0] {
1748                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
1749                         assert_eq!(our_payment_hash_21, *payment_hash);
1750                         assert_eq!(*payment_secret, None);
1751                         assert_eq!(recv_value_21, amt);
1752                 },
1753                 _ => panic!("Unexpected event"),
1754         }
1755         match events[1] {
1756                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
1757                         assert_eq!(our_payment_hash_22, *payment_hash);
1758                         assert_eq!(None, *payment_secret);
1759                         assert_eq!(recv_value_22, amt);
1760                 },
1761                 _ => panic!("Unexpected event"),
1762         }
1763
1764         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1, recv_value_1);
1765         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21, recv_value_21);
1766         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22, recv_value_22);
1767
1768         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);
1769         let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
1770         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
1771         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat);
1772
1773         let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
1774         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22);
1775 }
1776
1777 #[test]
1778 fn channel_reserve_test() {
1779         do_channel_reserve_test(false);
1780         do_channel_reserve_test(true);
1781 }
1782
1783 #[test]
1784 fn channel_reserve_in_flight_removes() {
1785         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
1786         // can send to its counterparty, but due to update ordering, the other side may not yet have
1787         // considered those HTLCs fully removed.
1788         // This tests that we don't count HTLCs which will not be included in the next remote
1789         // commitment transaction towards the reserve value (as it implies no commitment transaction
1790         // will be generated which violates the remote reserve value).
1791         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
1792         // To test this we:
1793         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
1794         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
1795         //    you only consider the value of the first HTLC, it may not),
1796         //  * start routing a third HTLC from A to B,
1797         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
1798         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
1799         //  * deliver the first fulfill from B
1800         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
1801         //    claim,
1802         //  * deliver A's response CS and RAA.
1803         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
1804         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
1805         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
1806         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
1807         let chanmon_cfgs = create_chanmon_cfgs(2);
1808         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1809         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1810         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1811         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1812         let logger = test_utils::TestLogger::new();
1813
1814         let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
1815         // Route the first two HTLCs.
1816         let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
1817         let (payment_preimage_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
1818
1819         // Start routing the third HTLC (this is just used to get everyone in the right state).
1820         let (payment_preimage_3, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
1821         let send_1 = {
1822                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1823                 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).unwrap();
1824                 nodes[0].node.send_payment(&route, payment_hash_3, &None).unwrap();
1825                 check_added_monitors!(nodes[0], 1);
1826                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1827                 assert_eq!(events.len(), 1);
1828                 SendEvent::from_event(events.remove(0))
1829         };
1830
1831         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
1832         // initial fulfill/CS.
1833         assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000));
1834         check_added_monitors!(nodes[1], 1);
1835         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1836
1837         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
1838         // remove the second HTLC when we send the HTLC back from B to A.
1839         assert!(nodes[1].node.claim_funds(payment_preimage_2, &None, 20000));
1840         check_added_monitors!(nodes[1], 1);
1841         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1842
1843         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
1844         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
1845         check_added_monitors!(nodes[0], 1);
1846         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1847         expect_payment_sent!(nodes[0], payment_preimage_1);
1848
1849         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
1850         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
1851         check_added_monitors!(nodes[1], 1);
1852         // B is already AwaitingRAA, so cant generate a CS here
1853         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1854
1855         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1856         check_added_monitors!(nodes[1], 1);
1857         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1858
1859         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1860         check_added_monitors!(nodes[0], 1);
1861         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1862
1863         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1864         check_added_monitors!(nodes[1], 1);
1865         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1866
1867         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
1868         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
1869         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
1870         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
1871         // on-chain as necessary).
1872         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
1873         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
1874         check_added_monitors!(nodes[0], 1);
1875         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1876         expect_payment_sent!(nodes[0], payment_preimage_2);
1877
1878         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1879         check_added_monitors!(nodes[1], 1);
1880         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1881
1882         expect_pending_htlcs_forwardable!(nodes[1]);
1883         expect_payment_received!(nodes[1], payment_hash_3, 100000);
1884
1885         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
1886         // resolve the second HTLC from A's point of view.
1887         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1888         check_added_monitors!(nodes[0], 1);
1889         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1890
1891         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
1892         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
1893         let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[1]);
1894         let send_2 = {
1895                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1896                 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).unwrap();
1897                 nodes[1].node.send_payment(&route, payment_hash_4, &None).unwrap();
1898                 check_added_monitors!(nodes[1], 1);
1899                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1900                 assert_eq!(events.len(), 1);
1901                 SendEvent::from_event(events.remove(0))
1902         };
1903
1904         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
1905         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
1906         check_added_monitors!(nodes[0], 1);
1907         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1908
1909         // Now just resolve all the outstanding messages/HTLCs for completeness...
1910
1911         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1912         check_added_monitors!(nodes[1], 1);
1913         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1914
1915         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1916         check_added_monitors!(nodes[1], 1);
1917
1918         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1919         check_added_monitors!(nodes[0], 1);
1920         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1921
1922         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1923         check_added_monitors!(nodes[1], 1);
1924         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1925
1926         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1927         check_added_monitors!(nodes[0], 1);
1928
1929         expect_pending_htlcs_forwardable!(nodes[0]);
1930         expect_payment_received!(nodes[0], payment_hash_4, 10000);
1931
1932         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4, 10_000);
1933         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3, 100_000);
1934 }
1935
1936 #[test]
1937 fn channel_monitor_network_test() {
1938         // Simple test which builds a network of ChannelManagers, connects them to each other, and
1939         // tests that ChannelMonitor is able to recover from various states.
1940         let chanmon_cfgs = create_chanmon_cfgs(5);
1941         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
1942         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
1943         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
1944
1945         // Create some initial channels
1946         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1947         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1948         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1949         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1950
1951         // Rebalance the network a bit by relaying one payment through all the channels...
1952         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
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
1957         // Simple case with no pending HTLCs:
1958         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
1959         check_added_monitors!(nodes[1], 1);
1960         {
1961                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
1962                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1963                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
1964                 check_added_monitors!(nodes[0], 1);
1965                 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
1966         }
1967         get_announce_close_broadcast_events(&nodes, 0, 1);
1968         assert_eq!(nodes[0].node.list_channels().len(), 0);
1969         assert_eq!(nodes[1].node.list_channels().len(), 1);
1970
1971         // One pending HTLC is discarded by the force-close:
1972         let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
1973
1974         // Simple case of one pending HTLC to HTLC-Timeout
1975         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
1976         check_added_monitors!(nodes[1], 1);
1977         {
1978                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
1979                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1980                 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
1981                 check_added_monitors!(nodes[2], 1);
1982                 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
1983         }
1984         get_announce_close_broadcast_events(&nodes, 1, 2);
1985         assert_eq!(nodes[1].node.list_channels().len(), 0);
1986         assert_eq!(nodes[2].node.list_channels().len(), 1);
1987
1988         macro_rules! claim_funds {
1989                 ($node: expr, $prev_node: expr, $preimage: expr, $amount: expr) => {
1990                         {
1991                                 assert!($node.node.claim_funds($preimage, &None, $amount));
1992                                 check_added_monitors!($node, 1);
1993
1994                                 let events = $node.node.get_and_clear_pending_msg_events();
1995                                 assert_eq!(events.len(), 1);
1996                                 match events[0] {
1997                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
1998                                                 assert!(update_add_htlcs.is_empty());
1999                                                 assert!(update_fail_htlcs.is_empty());
2000                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2001                                         },
2002                                         _ => panic!("Unexpected event"),
2003                                 };
2004                         }
2005                 }
2006         }
2007
2008         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2009         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2010         nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2011         check_added_monitors!(nodes[2], 1);
2012         let node2_commitment_txid;
2013         {
2014                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2015                 node2_commitment_txid = node_txn[0].txid();
2016
2017                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2018                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, 3_000_000);
2019
2020                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2021                 nodes[3].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
2022                 check_added_monitors!(nodes[3], 1);
2023
2024                 check_preimage_claim(&nodes[3], &node_txn);
2025         }
2026         get_announce_close_broadcast_events(&nodes, 2, 3);
2027         assert_eq!(nodes[2].node.list_channels().len(), 0);
2028         assert_eq!(nodes[3].node.list_channels().len(), 1);
2029
2030         { // Cheat and reset nodes[4]'s height to 1
2031                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2032                 nodes[4].block_notifier.block_connected(&Block { header, txdata: vec![] }, 1);
2033         }
2034
2035         assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
2036         assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
2037         // One pending HTLC to time out:
2038         let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2039         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2040         // buffer space).
2041
2042         {
2043                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2044                 nodes[3].block_notifier.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
2045                 for i in 3..TEST_FINAL_CLTV + 2 + LATENCY_GRACE_PERIOD_BLOCKS + 1 {
2046                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2047                         nodes[3].block_notifier.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
2048                 }
2049                 check_added_monitors!(nodes[3], 1);
2050
2051                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2052                 {
2053                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2054                         node_txn.retain(|tx| {
2055                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2056                                         false
2057                                 } else { true }
2058                         });
2059                 }
2060
2061                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2062
2063                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2064                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, 3_000_000);
2065
2066                 header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2067
2068                 nodes[4].block_notifier.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
2069                 for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
2070                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2071                         nodes[4].block_notifier.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
2072                 }
2073
2074                 check_added_monitors!(nodes[4], 1);
2075                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2076
2077                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2078                 nodes[4].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, TEST_FINAL_CLTV - 5);
2079
2080                 check_preimage_claim(&nodes[4], &node_txn);
2081         }
2082         get_announce_close_broadcast_events(&nodes, 3, 4);
2083         assert_eq!(nodes[3].node.list_channels().len(), 0);
2084         assert_eq!(nodes[4].node.list_channels().len(), 0);
2085 }
2086
2087 #[test]
2088 fn test_justice_tx() {
2089         // Test justice txn built on revoked HTLC-Success tx, against both sides
2090         let mut alice_config = UserConfig::default();
2091         alice_config.channel_options.announced_channel = true;
2092         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2093         alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2094         let mut bob_config = UserConfig::default();
2095         bob_config.channel_options.announced_channel = true;
2096         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2097         bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2098         let user_cfgs = [Some(alice_config), Some(bob_config)];
2099         let chanmon_cfgs = create_chanmon_cfgs(2);
2100         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2101         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2102         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2103         // Create some new channels:
2104         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2105
2106         // A pending HTLC which will be revoked:
2107         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2108         // Get the will-be-revoked local txn from nodes[0]
2109         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2110         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2111         assert_eq!(revoked_local_txn[0].input.len(), 1);
2112         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2113         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2114         assert_eq!(revoked_local_txn[1].input.len(), 1);
2115         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2116         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2117         // Revoke the old state
2118         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 3_000_000);
2119
2120         {
2121                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2122                 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2123                 {
2124                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2125                         assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2126                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2127
2128                         check_spends!(node_txn[0], revoked_local_txn[0]);
2129                         node_txn.swap_remove(0);
2130                         node_txn.truncate(1);
2131                 }
2132                 check_added_monitors!(nodes[1], 1);
2133                 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2134
2135                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2136                 // Verify broadcast of revoked HTLC-timeout
2137                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2138                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2139                 check_added_monitors!(nodes[0], 1);
2140                 // Broadcast revoked HTLC-timeout on node 1
2141                 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2142                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2143         }
2144         get_announce_close_broadcast_events(&nodes, 0, 1);
2145
2146         assert_eq!(nodes[0].node.list_channels().len(), 0);
2147         assert_eq!(nodes[1].node.list_channels().len(), 0);
2148
2149         // We test justice_tx build by A on B's revoked HTLC-Success tx
2150         // Create some new channels:
2151         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2152         {
2153                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2154                 node_txn.clear();
2155         }
2156
2157         // A pending HTLC which will be revoked:
2158         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2159         // Get the will-be-revoked local txn from B
2160         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2161         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2162         assert_eq!(revoked_local_txn[0].input.len(), 1);
2163         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2164         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2165         // Revoke the old state
2166         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4, 3_000_000);
2167         {
2168                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2169                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2170                 {
2171                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2172                         assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2173                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2174
2175                         check_spends!(node_txn[0], revoked_local_txn[0]);
2176                         node_txn.swap_remove(0);
2177                 }
2178                 check_added_monitors!(nodes[0], 1);
2179                 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2180
2181                 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2182                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2183                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2184                 check_added_monitors!(nodes[1], 1);
2185                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2186                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2187         }
2188         get_announce_close_broadcast_events(&nodes, 0, 1);
2189         assert_eq!(nodes[0].node.list_channels().len(), 0);
2190         assert_eq!(nodes[1].node.list_channels().len(), 0);
2191 }
2192
2193 #[test]
2194 fn revoked_output_claim() {
2195         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2196         // transaction is broadcast by its counterparty
2197         let chanmon_cfgs = create_chanmon_cfgs(2);
2198         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2199         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2200         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2201         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2202         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2203         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2204         assert_eq!(revoked_local_txn.len(), 1);
2205         // Only output is the full channel value back to nodes[0]:
2206         assert_eq!(revoked_local_txn[0].output.len(), 1);
2207         // Send a payment through, updating everyone's latest commitment txn
2208         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000, 5_000_000);
2209
2210         // Inform nodes[1] that nodes[0] broadcast a stale tx
2211         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2212         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2213         check_added_monitors!(nodes[1], 1);
2214         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2215         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2216
2217         check_spends!(node_txn[0], revoked_local_txn[0]);
2218         check_spends!(node_txn[1], chan_1.3);
2219
2220         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2221         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2222         get_announce_close_broadcast_events(&nodes, 0, 1);
2223         check_added_monitors!(nodes[0], 1)
2224 }
2225
2226 #[test]
2227 fn claim_htlc_outputs_shared_tx() {
2228         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2229         let chanmon_cfgs = create_chanmon_cfgs(2);
2230         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2231         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2232         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2233
2234         // Create some new channel:
2235         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2236
2237         // Rebalance the network to generate htlc in the two directions
2238         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2239         // 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
2240         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2241         let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2242
2243         // Get the will-be-revoked local txn from node[0]
2244         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2245         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2246         assert_eq!(revoked_local_txn[0].input.len(), 1);
2247         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2248         assert_eq!(revoked_local_txn[1].input.len(), 1);
2249         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2250         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2251         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2252
2253         //Revoke the old state
2254         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2255
2256         {
2257                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2258                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2259                 check_added_monitors!(nodes[0], 1);
2260                 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2261                 check_added_monitors!(nodes[1], 1);
2262                 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2263                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2264
2265                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2266                 assert_eq!(node_txn.len(), 3); // ChannelMonitor: penalty tx, ChannelManager: local commitment + HTLC-timeout
2267
2268                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2269                 check_spends!(node_txn[0], revoked_local_txn[0]);
2270
2271                 let mut witness_lens = BTreeSet::new();
2272                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2273                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2274                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2275                 assert_eq!(witness_lens.len(), 3);
2276                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2277                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2278                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2279
2280                 // Next nodes[1] broadcasts its current local tx state:
2281                 assert_eq!(node_txn[1].input.len(), 1);
2282                 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2283
2284                 assert_eq!(node_txn[2].input.len(), 1);
2285                 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
2286                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2287                 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
2288                 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
2289                 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
2290         }
2291         get_announce_close_broadcast_events(&nodes, 0, 1);
2292         assert_eq!(nodes[0].node.list_channels().len(), 0);
2293         assert_eq!(nodes[1].node.list_channels().len(), 0);
2294 }
2295
2296 #[test]
2297 fn claim_htlc_outputs_single_tx() {
2298         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2299         let chanmon_cfgs = create_chanmon_cfgs(2);
2300         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2301         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2302         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2303
2304         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2305
2306         // Rebalance the network to generate htlc in the two directions
2307         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2308         // 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
2309         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2310         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2311         let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2312
2313         // Get the will-be-revoked local txn from node[0]
2314         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2315
2316         //Revoke the old state
2317         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2318
2319         {
2320                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2321                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2322                 check_added_monitors!(nodes[0], 1);
2323                 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2324                 check_added_monitors!(nodes[1], 1);
2325                 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
2326
2327                 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 200, true, header.bitcoin_hash());
2328                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2329
2330                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2331                 assert_eq!(node_txn.len(), 9);
2332                 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2333                 // ChannelManager: local commmitment + local HTLC-timeout (2)
2334                 // 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)
2335                 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2336
2337                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2338                 assert_eq!(node_txn[2].input.len(), 1);
2339                 check_spends!(node_txn[2], chan_1.3);
2340                 assert_eq!(node_txn[3].input.len(), 1);
2341                 let witness_script = node_txn[3].input[0].witness.last().unwrap();
2342                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2343                 check_spends!(node_txn[3], node_txn[2]);
2344
2345                 // Justice transactions are indices 1-2-4
2346                 assert_eq!(node_txn[0].input.len(), 1);
2347                 assert_eq!(node_txn[1].input.len(), 1);
2348                 assert_eq!(node_txn[4].input.len(), 1);
2349
2350                 check_spends!(node_txn[0], revoked_local_txn[0]);
2351                 check_spends!(node_txn[1], revoked_local_txn[0]);
2352                 check_spends!(node_txn[4], revoked_local_txn[0]);
2353
2354                 let mut witness_lens = BTreeSet::new();
2355                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2356                 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2357                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2358                 assert_eq!(witness_lens.len(), 3);
2359                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2360                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2361                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2362         }
2363         get_announce_close_broadcast_events(&nodes, 0, 1);
2364         assert_eq!(nodes[0].node.list_channels().len(), 0);
2365         assert_eq!(nodes[1].node.list_channels().len(), 0);
2366 }
2367
2368 #[test]
2369 fn test_htlc_on_chain_success() {
2370         // Test that in case of a unilateral close onchain, we detect the state of output thanks to
2371         // ChainWatchInterface and pass the preimage backward accordingly. So here we test that ChannelManager is
2372         // broadcasting the right event to other nodes in payment path.
2373         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2374         // A --------------------> B ----------------------> C (preimage)
2375         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2376         // commitment transaction was broadcast.
2377         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2378         // towards B.
2379         // B should be able to claim via preimage if A then broadcasts its local tx.
2380         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2381         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2382         // PaymentSent event).
2383
2384         let chanmon_cfgs = create_chanmon_cfgs(3);
2385         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2386         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2387         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2388
2389         // Create some initial channels
2390         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2391         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2392
2393         // Rebalance the network a bit by relaying one payment through all the channels...
2394         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2395         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2396
2397         let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2398         let (our_payment_preimage_2, _payment_hash_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2399         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2400
2401         // Broadcast legit commitment tx from C on B's chain
2402         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2403         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2404         assert_eq!(commitment_tx.len(), 1);
2405         check_spends!(commitment_tx[0], chan_2.3);
2406         nodes[2].node.claim_funds(our_payment_preimage, &None, 3_000_000);
2407         nodes[2].node.claim_funds(our_payment_preimage_2, &None, 3_000_000);
2408         check_added_monitors!(nodes[2], 2);
2409         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2410         assert!(updates.update_add_htlcs.is_empty());
2411         assert!(updates.update_fail_htlcs.is_empty());
2412         assert!(updates.update_fail_malformed_htlcs.is_empty());
2413         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2414
2415         nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2416         check_closed_broadcast!(nodes[2], false);
2417         check_added_monitors!(nodes[2], 1);
2418         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)
2419         assert_eq!(node_txn.len(), 5);
2420         assert_eq!(node_txn[0], node_txn[3]);
2421         assert_eq!(node_txn[1], node_txn[4]);
2422         assert_eq!(node_txn[2], commitment_tx[0]);
2423         check_spends!(node_txn[0], commitment_tx[0]);
2424         check_spends!(node_txn[1], commitment_tx[0]);
2425         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2426         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2427         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2428         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2429         assert_eq!(node_txn[0].lock_time, 0);
2430         assert_eq!(node_txn[1].lock_time, 0);
2431
2432         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2433         nodes[1].block_notifier.block_connected(&Block { header, txdata: node_txn}, 1);
2434         {
2435                 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
2436                 assert_eq!(added_monitors.len(), 1);
2437                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2438                 added_monitors.clear();
2439         }
2440         let events = nodes[1].node.get_and_clear_pending_msg_events();
2441         {
2442                 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
2443                 assert_eq!(added_monitors.len(), 2);
2444                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2445                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2446                 added_monitors.clear();
2447         }
2448         assert_eq!(events.len(), 2);
2449         match events[0] {
2450                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2451                 _ => panic!("Unexpected event"),
2452         }
2453         match events[1] {
2454                 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, .. } } => {
2455                         assert!(update_add_htlcs.is_empty());
2456                         assert!(update_fail_htlcs.is_empty());
2457                         assert_eq!(update_fulfill_htlcs.len(), 1);
2458                         assert!(update_fail_malformed_htlcs.is_empty());
2459                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2460                 },
2461                 _ => panic!("Unexpected event"),
2462         };
2463         macro_rules! check_tx_local_broadcast {
2464                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2465                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2466                         assert_eq!(node_txn.len(), 5);
2467                         // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2468                         // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2469                         check_spends!(node_txn[0], $commitment_tx);
2470                         check_spends!(node_txn[1], $commitment_tx);
2471                         assert_ne!(node_txn[0].lock_time, 0);
2472                         assert_ne!(node_txn[1].lock_time, 0);
2473                         if $htlc_offered {
2474                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2475                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2476                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2477                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2478                         } else {
2479                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2480                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2481                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2482                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2483                         }
2484                         check_spends!(node_txn[2], $chan_tx);
2485                         check_spends!(node_txn[3], node_txn[2]);
2486                         check_spends!(node_txn[4], node_txn[2]);
2487                         assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), 71);
2488                         assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2489                         assert_eq!(node_txn[4].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2490                         assert!(node_txn[3].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2491                         assert!(node_txn[4].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2492                         assert_ne!(node_txn[3].lock_time, 0);
2493                         assert_ne!(node_txn[4].lock_time, 0);
2494                         node_txn.clear();
2495                 } }
2496         }
2497         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2498         // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2499         // timeout-claim of the output that nodes[2] just claimed via success.
2500         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2501
2502         // Broadcast legit commitment tx from A on B's chain
2503         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2504         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2505         check_spends!(commitment_tx[0], chan_1.3);
2506         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2507         check_closed_broadcast!(nodes[1], false);
2508         check_added_monitors!(nodes[1], 1);
2509         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 1 (HTLC-Success)
2510         assert_eq!(node_txn.len(), 4);
2511         check_spends!(node_txn[0], commitment_tx[0]);
2512         assert_eq!(node_txn[0].input.len(), 2);
2513         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2514         assert_eq!(node_txn[0].input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2515         assert_eq!(node_txn[0].lock_time, 0);
2516         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2517         check_spends!(node_txn[1], chan_1.3);
2518         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
2519         check_spends!(node_txn[2], node_txn[1]);
2520         check_spends!(node_txn[3], node_txn[1]);
2521         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2522         // we already checked the same situation with A.
2523
2524         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2525         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
2526         check_closed_broadcast!(nodes[0], false);
2527         check_added_monitors!(nodes[0], 1);
2528         let events = nodes[0].node.get_and_clear_pending_events();
2529         assert_eq!(events.len(), 2);
2530         let mut first_claimed = false;
2531         for event in events {
2532                 match event {
2533                         Event::PaymentSent { payment_preimage } => {
2534                                 if payment_preimage == our_payment_preimage {
2535                                         assert!(!first_claimed);
2536                                         first_claimed = true;
2537                                 } else {
2538                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2539                                 }
2540                         },
2541                         _ => panic!("Unexpected event"),
2542                 }
2543         }
2544         check_tx_local_broadcast!(nodes[0], true, commitment_tx[0], chan_1.3);
2545 }
2546
2547 #[test]
2548 fn test_htlc_on_chain_timeout() {
2549         // Test that in case of a unilateral close onchain, we detect the state of output thanks to
2550         // ChainWatchInterface and timeout the HTLC backward accordingly. So here we test that ChannelManager is
2551         // broadcasting the right event to other nodes in payment path.
2552         // A ------------------> B ----------------------> C (timeout)
2553         //    B's commitment tx                 C's commitment tx
2554         //            \                                  \
2555         //         B's HTLC timeout tx               B's timeout tx
2556
2557         let chanmon_cfgs = create_chanmon_cfgs(3);
2558         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2559         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2560         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2561
2562         // Create some intial channels
2563         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2564         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2565
2566         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2567         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2568         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2569
2570         let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2571         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2572
2573         // Broadcast legit commitment tx from C on B's chain
2574         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2575         check_spends!(commitment_tx[0], chan_2.3);
2576         nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
2577         check_added_monitors!(nodes[2], 0);
2578         expect_pending_htlcs_forwardable!(nodes[2]);
2579         check_added_monitors!(nodes[2], 1);
2580
2581         let events = nodes[2].node.get_and_clear_pending_msg_events();
2582         assert_eq!(events.len(), 1);
2583         match events[0] {
2584                 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, .. } } => {
2585                         assert!(update_add_htlcs.is_empty());
2586                         assert!(!update_fail_htlcs.is_empty());
2587                         assert!(update_fulfill_htlcs.is_empty());
2588                         assert!(update_fail_malformed_htlcs.is_empty());
2589                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2590                 },
2591                 _ => panic!("Unexpected event"),
2592         };
2593         nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2594         check_closed_broadcast!(nodes[2], false);
2595         check_added_monitors!(nodes[2], 1);
2596         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2597         assert_eq!(node_txn.len(), 1);
2598         check_spends!(node_txn[0], chan_2.3);
2599         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2600
2601         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2602         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2603         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
2604         let timeout_tx;
2605         {
2606                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2607                 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2608                 assert_eq!(node_txn[1], node_txn[3]);
2609                 assert_eq!(node_txn[2], node_txn[4]);
2610
2611                 check_spends!(node_txn[0], commitment_tx[0]);
2612                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2613
2614                 check_spends!(node_txn[1], chan_2.3);
2615                 check_spends!(node_txn[2], node_txn[1]);
2616                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
2617                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2618
2619                 timeout_tx = node_txn[0].clone();
2620                 node_txn.clear();
2621         }
2622
2623         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![timeout_tx]}, 1);
2624         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2625         check_added_monitors!(nodes[1], 1);
2626         check_closed_broadcast!(nodes[1], false);
2627
2628         expect_pending_htlcs_forwardable!(nodes[1]);
2629         check_added_monitors!(nodes[1], 1);
2630         let events = nodes[1].node.get_and_clear_pending_msg_events();
2631         assert_eq!(events.len(), 1);
2632         match events[0] {
2633                 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, .. } } => {
2634                         assert!(update_add_htlcs.is_empty());
2635                         assert!(!update_fail_htlcs.is_empty());
2636                         assert!(update_fulfill_htlcs.is_empty());
2637                         assert!(update_fail_malformed_htlcs.is_empty());
2638                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2639                 },
2640                 _ => panic!("Unexpected event"),
2641         };
2642         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
2643         assert_eq!(node_txn.len(), 0);
2644
2645         // Broadcast legit commitment tx from B on A's chain
2646         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2647         check_spends!(commitment_tx[0], chan_1.3);
2648
2649         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
2650         check_closed_broadcast!(nodes[0], false);
2651         check_added_monitors!(nodes[0], 1);
2652         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 1 timeout tx
2653         assert_eq!(node_txn.len(), 3);
2654         check_spends!(node_txn[0], commitment_tx[0]);
2655         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2656         check_spends!(node_txn[1], chan_1.3);
2657         check_spends!(node_txn[2], node_txn[1]);
2658         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
2659         assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2660 }
2661
2662 #[test]
2663 fn test_simple_commitment_revoked_fail_backward() {
2664         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
2665         // and fail backward accordingly.
2666
2667         let chanmon_cfgs = create_chanmon_cfgs(3);
2668         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2669         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2670         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2671
2672         // Create some initial channels
2673         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2674         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2675
2676         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2677         // Get the will-be-revoked local txn from nodes[2]
2678         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2679         // Revoke the old state
2680         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, 3_000_000);
2681
2682         let (_, payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2683
2684         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2685         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2686         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2687         check_added_monitors!(nodes[1], 1);
2688         check_closed_broadcast!(nodes[1], false);
2689
2690         expect_pending_htlcs_forwardable!(nodes[1]);
2691         check_added_monitors!(nodes[1], 1);
2692         let events = nodes[1].node.get_and_clear_pending_msg_events();
2693         assert_eq!(events.len(), 1);
2694         match events[0] {
2695                 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, .. } } => {
2696                         assert!(update_add_htlcs.is_empty());
2697                         assert_eq!(update_fail_htlcs.len(), 1);
2698                         assert!(update_fulfill_htlcs.is_empty());
2699                         assert!(update_fail_malformed_htlcs.is_empty());
2700                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2701
2702                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
2703                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2704
2705                         let events = nodes[0].node.get_and_clear_pending_msg_events();
2706                         assert_eq!(events.len(), 1);
2707                         match events[0] {
2708                                 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
2709                                 _ => panic!("Unexpected event"),
2710                         }
2711                         expect_payment_failed!(nodes[0], payment_hash, false);
2712                 },
2713                 _ => panic!("Unexpected event"),
2714         }
2715 }
2716
2717 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
2718         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
2719         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
2720         // commitment transaction anymore.
2721         // To do this, we have the peer which will broadcast a revoked commitment transaction send
2722         // a number of update_fail/commitment_signed updates without ever sending the RAA in
2723         // response to our commitment_signed. This is somewhat misbehavior-y, though not
2724         // technically disallowed and we should probably handle it reasonably.
2725         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
2726         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
2727         // transactions:
2728         // * Once we move it out of our holding cell/add it, we will immediately include it in a
2729         //   commitment_signed (implying it will be in the latest remote commitment transaction).
2730         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
2731         //   and once they revoke the previous commitment transaction (allowing us to send a new
2732         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
2733         let chanmon_cfgs = create_chanmon_cfgs(3);
2734         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2735         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2736         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2737
2738         // Create some initial channels
2739         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2740         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2741
2742         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
2743         // Get the will-be-revoked local txn from nodes[2]
2744         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2745         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
2746         // Revoke the old state
2747         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, if no_to_remote { 10_000 } else { 3_000_000});
2748
2749         let value = if use_dust {
2750                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
2751                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
2752                 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().our_dust_limit_satoshis * 1000
2753         } else { 3000000 };
2754
2755         let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2756         let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2757         let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2758
2759         assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, &None));
2760         expect_pending_htlcs_forwardable!(nodes[2]);
2761         check_added_monitors!(nodes[2], 1);
2762         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2763         assert!(updates.update_add_htlcs.is_empty());
2764         assert!(updates.update_fulfill_htlcs.is_empty());
2765         assert!(updates.update_fail_malformed_htlcs.is_empty());
2766         assert_eq!(updates.update_fail_htlcs.len(), 1);
2767         assert!(updates.update_fee.is_none());
2768         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2769         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
2770         // Drop the last RAA from 3 -> 2
2771
2772         assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, &None));
2773         expect_pending_htlcs_forwardable!(nodes[2]);
2774         check_added_monitors!(nodes[2], 1);
2775         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2776         assert!(updates.update_add_htlcs.is_empty());
2777         assert!(updates.update_fulfill_htlcs.is_empty());
2778         assert!(updates.update_fail_malformed_htlcs.is_empty());
2779         assert_eq!(updates.update_fail_htlcs.len(), 1);
2780         assert!(updates.update_fee.is_none());
2781         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2782         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
2783         check_added_monitors!(nodes[1], 1);
2784         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
2785         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2786         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
2787         check_added_monitors!(nodes[2], 1);
2788
2789         assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, &None));
2790         expect_pending_htlcs_forwardable!(nodes[2]);
2791         check_added_monitors!(nodes[2], 1);
2792         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2793         assert!(updates.update_add_htlcs.is_empty());
2794         assert!(updates.update_fulfill_htlcs.is_empty());
2795         assert!(updates.update_fail_malformed_htlcs.is_empty());
2796         assert_eq!(updates.update_fail_htlcs.len(), 1);
2797         assert!(updates.update_fee.is_none());
2798         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2799         // At this point first_payment_hash has dropped out of the latest two commitment
2800         // transactions that nodes[1] is tracking...
2801         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
2802         check_added_monitors!(nodes[1], 1);
2803         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
2804         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2805         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
2806         check_added_monitors!(nodes[2], 1);
2807
2808         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
2809         // on nodes[2]'s RAA.
2810         let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
2811         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
2812         let logger = test_utils::TestLogger::new();
2813         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).unwrap();
2814         nodes[1].node.send_payment(&route, fourth_payment_hash, &None).unwrap();
2815         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2816         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2817         check_added_monitors!(nodes[1], 0);
2818
2819         if deliver_bs_raa {
2820                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
2821                 // One monitor for the new revocation preimage, no second on as we won't generate a new
2822                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
2823                 check_added_monitors!(nodes[1], 1);
2824                 let events = nodes[1].node.get_and_clear_pending_events();
2825                 assert_eq!(events.len(), 1);
2826                 match events[0] {
2827                         Event::PendingHTLCsForwardable { .. } => { },
2828                         _ => panic!("Unexpected event"),
2829                 };
2830                 // Deliberately don't process the pending fail-back so they all fail back at once after
2831                 // block connection just like the !deliver_bs_raa case
2832         }
2833
2834         let mut failed_htlcs = HashSet::new();
2835         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2836
2837         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2838         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2839         check_added_monitors!(nodes[1], 1);
2840         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2841
2842         let events = nodes[1].node.get_and_clear_pending_events();
2843         assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
2844         match events[0] {
2845                 Event::PaymentFailed { ref payment_hash, .. } => {
2846                         assert_eq!(*payment_hash, fourth_payment_hash);
2847                 },
2848                 _ => panic!("Unexpected event"),
2849         }
2850         if !deliver_bs_raa {
2851                 match events[1] {
2852                         Event::PendingHTLCsForwardable { .. } => { },
2853                         _ => panic!("Unexpected event"),
2854                 };
2855         }
2856         nodes[1].node.process_pending_htlc_forwards();
2857         check_added_monitors!(nodes[1], 1);
2858
2859         let events = nodes[1].node.get_and_clear_pending_msg_events();
2860         assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
2861         match events[if deliver_bs_raa { 1 } else { 0 }] {
2862                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
2863                 _ => panic!("Unexpected event"),
2864         }
2865         if deliver_bs_raa {
2866                 match events[0] {
2867                         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, .. } } => {
2868                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
2869                                 assert_eq!(update_add_htlcs.len(), 1);
2870                                 assert!(update_fulfill_htlcs.is_empty());
2871                                 assert!(update_fail_htlcs.is_empty());
2872                                 assert!(update_fail_malformed_htlcs.is_empty());
2873                         },
2874                         _ => panic!("Unexpected event"),
2875                 }
2876         }
2877         match events[if deliver_bs_raa { 2 } else { 1 }] {
2878                 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, .. } } => {
2879                         assert!(update_add_htlcs.is_empty());
2880                         assert_eq!(update_fail_htlcs.len(), 3);
2881                         assert!(update_fulfill_htlcs.is_empty());
2882                         assert!(update_fail_malformed_htlcs.is_empty());
2883                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2884
2885                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
2886                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
2887                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
2888
2889                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2890
2891                         let events = nodes[0].node.get_and_clear_pending_msg_events();
2892                         // If we delivered B's RAA we got an unknown preimage error, not something
2893                         // that we should update our routing table for.
2894                         assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
2895                         for event in events {
2896                                 match event {
2897                                         MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
2898                                         _ => panic!("Unexpected event"),
2899                                 }
2900                         }
2901                         let events = nodes[0].node.get_and_clear_pending_events();
2902                         assert_eq!(events.len(), 3);
2903                         match events[0] {
2904                                 Event::PaymentFailed { ref payment_hash, .. } => {
2905                                         assert!(failed_htlcs.insert(payment_hash.0));
2906                                 },
2907                                 _ => panic!("Unexpected event"),
2908                         }
2909                         match events[1] {
2910                                 Event::PaymentFailed { ref payment_hash, .. } => {
2911                                         assert!(failed_htlcs.insert(payment_hash.0));
2912                                 },
2913                                 _ => panic!("Unexpected event"),
2914                         }
2915                         match events[2] {
2916                                 Event::PaymentFailed { ref payment_hash, .. } => {
2917                                         assert!(failed_htlcs.insert(payment_hash.0));
2918                                 },
2919                                 _ => panic!("Unexpected event"),
2920                         }
2921                 },
2922                 _ => panic!("Unexpected event"),
2923         }
2924
2925         assert!(failed_htlcs.contains(&first_payment_hash.0));
2926         assert!(failed_htlcs.contains(&second_payment_hash.0));
2927         assert!(failed_htlcs.contains(&third_payment_hash.0));
2928 }
2929
2930 #[test]
2931 fn test_commitment_revoked_fail_backward_exhaustive_a() {
2932         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
2933         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
2934         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
2935         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
2936 }
2937
2938 #[test]
2939 fn test_commitment_revoked_fail_backward_exhaustive_b() {
2940         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
2941         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
2942         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
2943         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
2944 }
2945
2946 #[test]
2947 fn fail_backward_pending_htlc_upon_channel_failure() {
2948         let chanmon_cfgs = create_chanmon_cfgs(2);
2949         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2950         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2951         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2952         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
2953         let logger = test_utils::TestLogger::new();
2954
2955         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
2956         {
2957                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
2958                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
2959                 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).unwrap();
2960                 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
2961                 check_added_monitors!(nodes[0], 1);
2962
2963                 let payment_event = {
2964                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2965                         assert_eq!(events.len(), 1);
2966                         SendEvent::from_event(events.remove(0))
2967                 };
2968                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
2969                 assert_eq!(payment_event.msgs.len(), 1);
2970         }
2971
2972         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
2973         let (_, failed_payment_hash) = get_payment_preimage_hash!(nodes[0]);
2974         {
2975                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
2976                 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).unwrap();
2977                 nodes[0].node.send_payment(&route, failed_payment_hash, &None).unwrap();
2978                 check_added_monitors!(nodes[0], 0);
2979
2980                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2981         }
2982
2983         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
2984         {
2985                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[1]);
2986
2987                 let secp_ctx = Secp256k1::new();
2988                 let session_priv = {
2989                         let mut session_key = [0; 32];
2990                         let mut rng = thread_rng();
2991                         rng.fill_bytes(&mut session_key);
2992                         SecretKey::from_slice(&session_key).expect("RNG is bad!")
2993                 };
2994
2995                 let current_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
2996                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
2997                 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).unwrap();
2998                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &None, current_height).unwrap();
2999                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3000                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3001
3002                 // Send a 0-msat update_add_htlc to fail the channel.
3003                 let update_add_htlc = msgs::UpdateAddHTLC {
3004                         channel_id: chan.2,
3005                         htlc_id: 0,
3006                         amount_msat: 0,
3007                         payment_hash,
3008                         cltv_expiry,
3009                         onion_routing_packet,
3010                 };
3011                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3012         }
3013
3014         // Check that Alice fails backward the pending HTLC from the second payment.
3015         expect_payment_failed!(nodes[0], failed_payment_hash, true);
3016         check_closed_broadcast!(nodes[0], true);
3017         check_added_monitors!(nodes[0], 1);
3018 }
3019
3020 #[test]
3021 fn test_htlc_ignore_latest_remote_commitment() {
3022         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3023         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3024         let chanmon_cfgs = create_chanmon_cfgs(2);
3025         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3026         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3027         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3028         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3029
3030         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3031         nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
3032         check_closed_broadcast!(nodes[0], false);
3033         check_added_monitors!(nodes[0], 1);
3034
3035         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3036         assert_eq!(node_txn.len(), 2);
3037
3038         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3039         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3040         check_closed_broadcast!(nodes[1], false);
3041         check_added_monitors!(nodes[1], 1);
3042
3043         // Duplicate the block_connected call since this may happen due to other listeners
3044         // registering new transactions
3045         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3046 }
3047
3048 #[test]
3049 fn test_force_close_fail_back() {
3050         // Check which HTLCs are failed-backwards on channel force-closure
3051         let chanmon_cfgs = create_chanmon_cfgs(3);
3052         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3053         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3054         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3055         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3056         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3057         let logger = test_utils::TestLogger::new();
3058
3059         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3060
3061         let mut payment_event = {
3062                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3063                 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).unwrap();
3064                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
3065                 check_added_monitors!(nodes[0], 1);
3066
3067                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3068                 assert_eq!(events.len(), 1);
3069                 SendEvent::from_event(events.remove(0))
3070         };
3071
3072         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3073         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3074
3075         expect_pending_htlcs_forwardable!(nodes[1]);
3076
3077         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3078         assert_eq!(events_2.len(), 1);
3079         payment_event = SendEvent::from_event(events_2.remove(0));
3080         assert_eq!(payment_event.msgs.len(), 1);
3081
3082         check_added_monitors!(nodes[1], 1);
3083         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3084         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3085         check_added_monitors!(nodes[2], 1);
3086         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3087
3088         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3089         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3090         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3091
3092         nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
3093         check_closed_broadcast!(nodes[2], false);
3094         check_added_monitors!(nodes[2], 1);
3095         let tx = {
3096                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3097                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3098                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3099                 // back to nodes[1] upon timeout otherwise.
3100                 assert_eq!(node_txn.len(), 1);
3101                 node_txn.remove(0)
3102         };
3103
3104         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3105         nodes[1].block_notifier.block_connected_checked(&header, 1, &[&tx], &[1]);
3106
3107         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3108         check_closed_broadcast!(nodes[1], false);
3109         check_added_monitors!(nodes[1], 1);
3110
3111         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3112         {
3113                 let mut monitors = nodes[2].chan_monitor.simple_monitor.monitors.lock().unwrap();
3114                 monitors.get_mut(&OutPoint{ txid: Txid::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), index: 0 }).unwrap()
3115                         .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
3116         }
3117         nodes[2].block_notifier.block_connected_checked(&header, 1, &[&tx], &[1]);
3118         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3119         assert_eq!(node_txn.len(), 1);
3120         assert_eq!(node_txn[0].input.len(), 1);
3121         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3122         assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3123         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3124
3125         check_spends!(node_txn[0], tx);
3126 }
3127
3128 #[test]
3129 fn test_unconf_chan() {
3130         // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
3131         let chanmon_cfgs = create_chanmon_cfgs(2);
3132         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3133         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3134         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3135         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3136
3137         let channel_state = nodes[0].node.channel_state.lock().unwrap();
3138         assert_eq!(channel_state.by_id.len(), 1);
3139         assert_eq!(channel_state.short_to_id.len(), 1);
3140         mem::drop(channel_state);
3141
3142         let mut headers = Vec::new();
3143         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3144         headers.push(header.clone());
3145         for _i in 2..100 {
3146                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3147                 headers.push(header.clone());
3148         }
3149         let mut height = 99;
3150         while !headers.is_empty() {
3151                 nodes[0].node.block_disconnected(&headers.pop().unwrap(), height);
3152                 height -= 1;
3153         }
3154         check_closed_broadcast!(nodes[0], false);
3155         check_added_monitors!(nodes[0], 1);
3156         let channel_state = nodes[0].node.channel_state.lock().unwrap();
3157         assert_eq!(channel_state.by_id.len(), 0);
3158         assert_eq!(channel_state.short_to_id.len(), 0);
3159 }
3160
3161 #[test]
3162 fn test_simple_peer_disconnect() {
3163         // Test that we can reconnect when there are no lost messages
3164         let chanmon_cfgs = create_chanmon_cfgs(3);
3165         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3166         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3167         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3168         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3169         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3170
3171         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3172         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3173         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3174
3175         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3176         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3177         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3178         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1, 1_000_000);
3179
3180         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3181         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3182         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3183
3184         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3185         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3186         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3187         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3188
3189         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3190         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3191
3192         claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3, 1_000_000);
3193         fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
3194
3195         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3196         {
3197                 let events = nodes[0].node.get_and_clear_pending_events();
3198                 assert_eq!(events.len(), 2);
3199                 match events[0] {
3200                         Event::PaymentSent { payment_preimage } => {
3201                                 assert_eq!(payment_preimage, payment_preimage_3);
3202                         },
3203                         _ => panic!("Unexpected event"),
3204                 }
3205                 match events[1] {
3206                         Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
3207                                 assert_eq!(payment_hash, payment_hash_5);
3208                                 assert!(rejected_by_dest);
3209                         },
3210                         _ => panic!("Unexpected event"),
3211                 }
3212         }
3213
3214         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4, 1_000_000);
3215         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3216 }
3217
3218 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
3219         // Test that we can reconnect when in-flight HTLC updates get dropped
3220         let chanmon_cfgs = create_chanmon_cfgs(2);
3221         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3222         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3223         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3224         if messages_delivered == 0 {
3225                 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3226                 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3227         } else {
3228                 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3229         }
3230
3231         let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
3232
3233         let logger = test_utils::TestLogger::new();
3234         let payment_event = {
3235                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3236                 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).unwrap();
3237                 nodes[0].node.send_payment(&route, payment_hash_1, &None).unwrap();
3238                 check_added_monitors!(nodes[0], 1);
3239
3240                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3241                 assert_eq!(events.len(), 1);
3242                 SendEvent::from_event(events.remove(0))
3243         };
3244         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3245
3246         if messages_delivered < 2 {
3247                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3248         } else {
3249                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3250                 if messages_delivered >= 3 {
3251                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3252                         check_added_monitors!(nodes[1], 1);
3253                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3254
3255                         if messages_delivered >= 4 {
3256                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3257                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3258                                 check_added_monitors!(nodes[0], 1);
3259
3260                                 if messages_delivered >= 5 {
3261                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3262                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3263                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3264                                         check_added_monitors!(nodes[0], 1);
3265
3266                                         if messages_delivered >= 6 {
3267                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3268                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3269                                                 check_added_monitors!(nodes[1], 1);
3270                                         }
3271                                 }
3272                         }
3273                 }
3274         }
3275
3276         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3277         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3278         if messages_delivered < 3 {
3279                 // Even if the funding_locked messages get exchanged, as long as nothing further was
3280                 // received on either side, both sides will need to resend them.
3281                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
3282         } else if messages_delivered == 3 {
3283                 // nodes[0] still wants its RAA + commitment_signed
3284                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
3285         } else if messages_delivered == 4 {
3286                 // nodes[0] still wants its commitment_signed
3287                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3288         } else if messages_delivered == 5 {
3289                 // nodes[1] still wants its final RAA
3290                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3291         } else if messages_delivered == 6 {
3292                 // Everything was delivered...
3293                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3294         }
3295
3296         let events_1 = nodes[1].node.get_and_clear_pending_events();
3297         assert_eq!(events_1.len(), 1);
3298         match events_1[0] {
3299                 Event::PendingHTLCsForwardable { .. } => { },
3300                 _ => panic!("Unexpected event"),
3301         };
3302
3303         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3304         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3305         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3306
3307         nodes[1].node.process_pending_htlc_forwards();
3308
3309         let events_2 = nodes[1].node.get_and_clear_pending_events();
3310         assert_eq!(events_2.len(), 1);
3311         match events_2[0] {
3312                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
3313                         assert_eq!(payment_hash_1, *payment_hash);
3314                         assert_eq!(*payment_secret, None);
3315                         assert_eq!(amt, 1000000);
3316                 },
3317                 _ => panic!("Unexpected event"),
3318         }
3319
3320         nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000);
3321         check_added_monitors!(nodes[1], 1);
3322
3323         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3324         assert_eq!(events_3.len(), 1);
3325         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3326                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3327                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3328                         assert!(updates.update_add_htlcs.is_empty());
3329                         assert!(updates.update_fail_htlcs.is_empty());
3330                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3331                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3332                         assert!(updates.update_fee.is_none());
3333                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3334                 },
3335                 _ => panic!("Unexpected event"),
3336         };
3337
3338         if messages_delivered >= 1 {
3339                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3340
3341                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3342                 assert_eq!(events_4.len(), 1);
3343                 match events_4[0] {
3344                         Event::PaymentSent { ref payment_preimage } => {
3345                                 assert_eq!(payment_preimage_1, *payment_preimage);
3346                         },
3347                         _ => panic!("Unexpected event"),
3348                 }
3349
3350                 if messages_delivered >= 2 {
3351                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3352                         check_added_monitors!(nodes[0], 1);
3353                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3354
3355                         if messages_delivered >= 3 {
3356                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3357                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3358                                 check_added_monitors!(nodes[1], 1);
3359
3360                                 if messages_delivered >= 4 {
3361                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3362                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3363                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3364                                         check_added_monitors!(nodes[1], 1);
3365
3366                                         if messages_delivered >= 5 {
3367                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3368                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3369                                                 check_added_monitors!(nodes[0], 1);
3370                                         }
3371                                 }
3372                         }
3373                 }
3374         }
3375
3376         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3377         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3378         if messages_delivered < 2 {
3379                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
3380                 //TODO: Deduplicate PaymentSent events, then enable this if:
3381                 //if messages_delivered < 1 {
3382                         let events_4 = nodes[0].node.get_and_clear_pending_events();
3383                         assert_eq!(events_4.len(), 1);
3384                         match events_4[0] {
3385                                 Event::PaymentSent { ref payment_preimage } => {
3386                                         assert_eq!(payment_preimage_1, *payment_preimage);
3387                                 },
3388                                 _ => panic!("Unexpected event"),
3389                         }
3390                 //}
3391         } else if messages_delivered == 2 {
3392                 // nodes[0] still wants its RAA + commitment_signed
3393                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
3394         } else if messages_delivered == 3 {
3395                 // nodes[0] still wants its commitment_signed
3396                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
3397         } else if messages_delivered == 4 {
3398                 // nodes[1] still wants its final RAA
3399                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3400         } else if messages_delivered == 5 {
3401                 // Everything was delivered...
3402                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3403         }
3404
3405         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3406         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3407         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3408
3409         // Channel should still work fine...
3410         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3411         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).unwrap();
3412         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3413         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3414 }
3415
3416 #[test]
3417 fn test_drop_messages_peer_disconnect_a() {
3418         do_test_drop_messages_peer_disconnect(0);
3419         do_test_drop_messages_peer_disconnect(1);
3420         do_test_drop_messages_peer_disconnect(2);
3421         do_test_drop_messages_peer_disconnect(3);
3422 }
3423
3424 #[test]
3425 fn test_drop_messages_peer_disconnect_b() {
3426         do_test_drop_messages_peer_disconnect(4);
3427         do_test_drop_messages_peer_disconnect(5);
3428         do_test_drop_messages_peer_disconnect(6);
3429 }
3430
3431 #[test]
3432 fn test_funding_peer_disconnect() {
3433         // Test that we can lock in our funding tx while disconnected
3434         let chanmon_cfgs = create_chanmon_cfgs(2);
3435         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3436         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3437         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3438         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3439
3440         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3441         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3442
3443         confirm_transaction(&nodes[0].block_notifier, &nodes[0].chain_monitor, &tx, tx.version);
3444         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3445         assert_eq!(events_1.len(), 1);
3446         match events_1[0] {
3447                 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3448                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3449                 },
3450                 _ => panic!("Unexpected event"),
3451         }
3452
3453         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3454
3455         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3456         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3457
3458         confirm_transaction(&nodes[1].block_notifier, &nodes[1].chain_monitor, &tx, tx.version);
3459         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3460         assert_eq!(events_2.len(), 2);
3461         let funding_locked = match events_2[0] {
3462                 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3463                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3464                         msg.clone()
3465                 },
3466                 _ => panic!("Unexpected event"),
3467         };
3468         let bs_announcement_sigs = match events_2[1] {
3469                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3470                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3471                         msg.clone()
3472                 },
3473                 _ => panic!("Unexpected event"),
3474         };
3475
3476         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3477
3478         nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3479         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3480         let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3481         assert_eq!(events_3.len(), 2);
3482         let as_announcement_sigs = match events_3[0] {
3483                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3484                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3485                         msg.clone()
3486                 },
3487                 _ => panic!("Unexpected event"),
3488         };
3489         let (as_announcement, as_update) = match events_3[1] {
3490                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3491                         (msg.clone(), update_msg.clone())
3492                 },
3493                 _ => panic!("Unexpected event"),
3494         };
3495
3496         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3497         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3498         assert_eq!(events_4.len(), 1);
3499         let (_, bs_update) = match events_4[0] {
3500                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3501                         (msg.clone(), update_msg.clone())
3502                 },
3503                 _ => panic!("Unexpected event"),
3504         };
3505
3506         nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3507         nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3508         nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3509
3510         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3511         let logger = test_utils::TestLogger::new();
3512         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).unwrap();
3513         let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3514         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage, 1_000_000);
3515 }
3516
3517 #[test]
3518 fn test_drop_messages_peer_disconnect_dual_htlc() {
3519         // Test that we can handle reconnecting when both sides of a channel have pending
3520         // commitment_updates when we disconnect.
3521         let chanmon_cfgs = create_chanmon_cfgs(2);
3522         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3523         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3524         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3525         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3526         let logger = test_utils::TestLogger::new();
3527
3528         let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3529
3530         // Now try to send a second payment which will fail to send
3531         let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
3532         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3533         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).unwrap();
3534         nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
3535         check_added_monitors!(nodes[0], 1);
3536
3537         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3538         assert_eq!(events_1.len(), 1);
3539         match events_1[0] {
3540                 MessageSendEvent::UpdateHTLCs { .. } => {},
3541                 _ => panic!("Unexpected event"),
3542         }
3543
3544         assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000));
3545         check_added_monitors!(nodes[1], 1);
3546
3547         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3548         assert_eq!(events_2.len(), 1);
3549         match events_2[0] {
3550                 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 } } => {
3551                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3552                         assert!(update_add_htlcs.is_empty());
3553                         assert_eq!(update_fulfill_htlcs.len(), 1);
3554                         assert!(update_fail_htlcs.is_empty());
3555                         assert!(update_fail_malformed_htlcs.is_empty());
3556                         assert!(update_fee.is_none());
3557
3558                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3559                         let events_3 = nodes[0].node.get_and_clear_pending_events();
3560                         assert_eq!(events_3.len(), 1);
3561                         match events_3[0] {
3562                                 Event::PaymentSent { ref payment_preimage } => {
3563                                         assert_eq!(*payment_preimage, payment_preimage_1);
3564                                 },
3565                                 _ => panic!("Unexpected event"),
3566                         }
3567
3568                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3569                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3570                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3571                         check_added_monitors!(nodes[0], 1);
3572                 },
3573                 _ => panic!("Unexpected event"),
3574         }
3575
3576         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3577         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3578
3579         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3580         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3581         assert_eq!(reestablish_1.len(), 1);
3582         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3583         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3584         assert_eq!(reestablish_2.len(), 1);
3585
3586         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3587         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3588         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3589         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3590
3591         assert!(as_resp.0.is_none());
3592         assert!(bs_resp.0.is_none());
3593
3594         assert!(bs_resp.1.is_none());
3595         assert!(bs_resp.2.is_none());
3596
3597         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3598
3599         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3600         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3601         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3602         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3603         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3604         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
3605         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
3606         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3607         // No commitment_signed so get_event_msg's assert(len == 1) passes
3608         check_added_monitors!(nodes[1], 1);
3609
3610         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
3611         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3612         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3613         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3614         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3615         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3616         assert!(bs_second_commitment_signed.update_fee.is_none());
3617         check_added_monitors!(nodes[1], 1);
3618
3619         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3620         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3621         assert!(as_commitment_signed.update_add_htlcs.is_empty());
3622         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
3623         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
3624         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
3625         assert!(as_commitment_signed.update_fee.is_none());
3626         check_added_monitors!(nodes[0], 1);
3627
3628         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
3629         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3630         // No commitment_signed so get_event_msg's assert(len == 1) passes
3631         check_added_monitors!(nodes[0], 1);
3632
3633         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
3634         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3635         // No commitment_signed so get_event_msg's assert(len == 1) passes
3636         check_added_monitors!(nodes[1], 1);
3637
3638         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3639         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3640         check_added_monitors!(nodes[1], 1);
3641
3642         expect_pending_htlcs_forwardable!(nodes[1]);
3643
3644         let events_5 = nodes[1].node.get_and_clear_pending_events();
3645         assert_eq!(events_5.len(), 1);
3646         match events_5[0] {
3647                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt: _ } => {
3648                         assert_eq!(payment_hash_2, *payment_hash);
3649                         assert_eq!(*payment_secret, None);
3650                 },
3651                 _ => panic!("Unexpected event"),
3652         }
3653
3654         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
3655         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3656         check_added_monitors!(nodes[0], 1);
3657
3658         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3659 }
3660
3661 fn do_test_htlc_timeout(send_partial_mpp: bool) {
3662         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
3663         // to avoid our counterparty failing the channel.
3664         let chanmon_cfgs = create_chanmon_cfgs(2);
3665         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3666         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3667         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3668
3669         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3670         let logger = test_utils::TestLogger::new();
3671
3672         let our_payment_hash = if send_partial_mpp {
3673                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3674                 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).unwrap();
3675                 let (_, our_payment_hash) = get_payment_preimage_hash!(&nodes[0]);
3676                 let payment_secret = PaymentSecret([0xdb; 32]);
3677                 // Use the utility function send_payment_along_path to send the payment with MPP data which
3678                 // indicates there are more HTLCs coming.
3679                 nodes[0].node.send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200000, CHAN_CONFIRM_DEPTH).unwrap();
3680                 check_added_monitors!(nodes[0], 1);
3681                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3682                 assert_eq!(events.len(), 1);
3683                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
3684                 // hop should *not* yet generate any PaymentReceived event(s).
3685                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false);
3686                 our_payment_hash
3687         } else {
3688                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
3689         };
3690
3691         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3692         nodes[0].block_notifier.block_connected_checked(&header, 101, &[], &[]);
3693         nodes[1].block_notifier.block_connected_checked(&header, 101, &[], &[]);
3694         for i in 102..TEST_FINAL_CLTV + 100 + 1 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
3695                 header.prev_blockhash = header.bitcoin_hash();
3696                 nodes[0].block_notifier.block_connected_checked(&header, i, &[], &[]);
3697                 nodes[1].block_notifier.block_connected_checked(&header, i, &[], &[]);
3698         }
3699
3700         expect_pending_htlcs_forwardable!(nodes[1]);
3701
3702         check_added_monitors!(nodes[1], 1);
3703         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3704         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
3705         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
3706         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
3707         assert!(htlc_timeout_updates.update_fee.is_none());
3708
3709         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
3710         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
3711         // 100_000 msat as u64, followed by a height of 123 as u32
3712         let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
3713         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(123));
3714         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
3715 }
3716
3717 #[test]
3718 fn test_htlc_timeout() {
3719         do_test_htlc_timeout(true);
3720         do_test_htlc_timeout(false);
3721 }
3722
3723 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
3724         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
3725         let chanmon_cfgs = create_chanmon_cfgs(3);
3726         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3727         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3728         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3729         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3730         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3731         let logger = test_utils::TestLogger::new();
3732
3733         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
3734         let (_, first_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3735         {
3736                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3737                 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).unwrap();
3738                 nodes[1].node.send_payment(&route, first_payment_hash, &None).unwrap();
3739         }
3740         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
3741         check_added_monitors!(nodes[1], 1);
3742
3743         // Now attempt to route a second payment, which should be placed in the holding cell
3744         let (_, second_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3745         if forwarded_htlc {
3746                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3747                 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).unwrap();
3748                 nodes[0].node.send_payment(&route, second_payment_hash, &None).unwrap();
3749                 check_added_monitors!(nodes[0], 1);
3750                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
3751                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3752                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3753                 expect_pending_htlcs_forwardable!(nodes[1]);
3754                 check_added_monitors!(nodes[1], 0);
3755         } else {
3756                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3757                 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).unwrap();
3758                 nodes[1].node.send_payment(&route, second_payment_hash, &None).unwrap();
3759                 check_added_monitors!(nodes[1], 0);
3760         }
3761
3762         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3763         nodes[1].block_notifier.block_connected_checked(&header, 101, &[], &[]);
3764         for i in 102..TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
3765                 header.prev_blockhash = header.bitcoin_hash();
3766                 nodes[1].block_notifier.block_connected_checked(&header, i, &[], &[]);
3767         }
3768
3769         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3770         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3771
3772         header.prev_blockhash = header.bitcoin_hash();
3773         nodes[1].block_notifier.block_connected_checked(&header, TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS, &[], &[]);
3774
3775         if forwarded_htlc {
3776                 expect_pending_htlcs_forwardable!(nodes[1]);
3777                 check_added_monitors!(nodes[1], 1);
3778                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
3779                 assert_eq!(fail_commit.len(), 1);
3780                 match fail_commit[0] {
3781                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
3782                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3783                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
3784                         },
3785                         _ => unreachable!(),
3786                 }
3787                 expect_payment_failed!(nodes[0], second_payment_hash, false);
3788                 if let &MessageSendEvent::PaymentFailureNetworkUpdate { ref update } = &nodes[0].node.get_and_clear_pending_msg_events()[0] {
3789                         match update {
3790                                 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {},
3791                                 _ => panic!("Unexpected event"),
3792                         }
3793                 } else {
3794                         panic!("Unexpected event");
3795                 }
3796         } else {
3797                 expect_payment_failed!(nodes[1], second_payment_hash, true);
3798         }
3799 }
3800
3801 #[test]
3802 fn test_holding_cell_htlc_add_timeouts() {
3803         do_test_holding_cell_htlc_add_timeouts(false);
3804         do_test_holding_cell_htlc_add_timeouts(true);
3805 }
3806
3807 #[test]
3808 fn test_invalid_channel_announcement() {
3809         //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
3810         let secp_ctx = Secp256k1::new();
3811         let chanmon_cfgs = create_chanmon_cfgs(2);
3812         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3813         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3814         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3815
3816         let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
3817
3818         let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
3819         let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
3820         let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
3821         let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
3822
3823         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 } );
3824
3825         let as_bitcoin_key = as_chan.get_local_keys().inner.local_channel_pubkeys.funding_pubkey;
3826         let bs_bitcoin_key = bs_chan.get_local_keys().inner.local_channel_pubkeys.funding_pubkey;
3827
3828         let as_network_key = nodes[0].node.get_our_node_id();
3829         let bs_network_key = nodes[1].node.get_our_node_id();
3830
3831         let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
3832
3833         let mut chan_announcement;
3834
3835         macro_rules! dummy_unsigned_msg {
3836                 () => {
3837                         msgs::UnsignedChannelAnnouncement {
3838                                 features: ChannelFeatures::known(),
3839                                 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
3840                                 short_channel_id: as_chan.get_short_channel_id().unwrap(),
3841                                 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
3842                                 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
3843                                 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
3844                                 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
3845                                 excess_data: Vec::new(),
3846                         };
3847                 }
3848         }
3849
3850         macro_rules! sign_msg {
3851                 ($unsigned_msg: expr) => {
3852                         let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
3853                         let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_local_keys().inner.funding_key());
3854                         let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_local_keys().inner.funding_key());
3855                         let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
3856                         let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
3857                         chan_announcement = msgs::ChannelAnnouncement {
3858                                 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
3859                                 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
3860                                 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
3861                                 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
3862                                 contents: $unsigned_msg
3863                         }
3864                 }
3865         }
3866
3867         let unsigned_msg = dummy_unsigned_msg!();
3868         sign_msg!(unsigned_msg);
3869         assert_eq!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap(), true);
3870         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 } );
3871
3872         // Configured with Network::Testnet
3873         let mut unsigned_msg = dummy_unsigned_msg!();
3874         unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.bitcoin_hash();
3875         sign_msg!(unsigned_msg);
3876         assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
3877
3878         let mut unsigned_msg = dummy_unsigned_msg!();
3879         unsigned_msg.chain_hash = BlockHash::hash(&[1,2,3,4,5,6,7,8,9]);
3880         sign_msg!(unsigned_msg);
3881         assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
3882 }
3883
3884 #[test]
3885 fn test_no_txn_manager_serialize_deserialize() {
3886         let chanmon_cfgs = create_chanmon_cfgs(2);
3887         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3888         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3889         let logger: test_utils::TestLogger;
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, &test_utils::TestLogger>;
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         logger = test_utils::TestLogger::new();
3905         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
3906         new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator);
3907         nodes[0].chan_monitor = &new_chan_monitor;
3908         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3909         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read).unwrap();
3910         assert!(chan_0_monitor_read.is_empty());
3911
3912         let mut nodes_0_read = &nodes_0_serialized[..];
3913         let config = UserConfig::default();
3914         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
3915         let (_, nodes_0_deserialized_tmp) = {
3916                 let mut channel_monitors = HashMap::new();
3917                 channel_monitors.insert(chan_0_monitor.get_funding_txo(), &mut chan_0_monitor);
3918                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3919                         default_config: config,
3920                         keys_manager: &keys_manager,
3921                         fee_estimator: &fee_estimator,
3922                         monitor: nodes[0].chan_monitor,
3923                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3924                         logger: &logger,
3925                         channel_monitors: &mut channel_monitors,
3926                 }).unwrap()
3927         };
3928         nodes_0_deserialized = nodes_0_deserialized_tmp;
3929         assert!(nodes_0_read.is_empty());
3930
3931         assert!(nodes[0].chan_monitor.add_monitor(chan_0_monitor.get_funding_txo(), chan_0_monitor).is_ok());
3932         nodes[0].node = &nodes_0_deserialized;
3933         nodes[0].block_notifier.register_listener(nodes[0].node);
3934         assert_eq!(nodes[0].node.list_channels().len(), 1);
3935         check_added_monitors!(nodes[0], 1);
3936
3937         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3938         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3939         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3940         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3941
3942         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3943         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3944         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3945         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3946
3947         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
3948         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
3949         for node in nodes.iter() {
3950                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
3951                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3952                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3953         }
3954
3955         send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
3956 }
3957
3958 #[test]
3959 fn test_manager_serialize_deserialize_events() {
3960         // This test makes sure the events field in ChannelManager survives de/serialization
3961         let chanmon_cfgs = create_chanmon_cfgs(2);
3962         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3963         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3964         let fee_estimator: test_utils::TestFeeEstimator;
3965         let logger: test_utils::TestLogger;
3966         let new_chan_monitor: test_utils::TestChannelMonitor;
3967         let keys_manager: test_utils::TestKeysInterface;
3968         let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3969         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3970
3971         // Start creating a channel, but stop right before broadcasting the event message FundingBroadcastSafe
3972         let channel_value = 100000;
3973         let push_msat = 10001;
3974         let a_flags = InitFeatures::known();
3975         let b_flags = InitFeatures::known();
3976         let node_a = nodes.pop().unwrap();
3977         let node_b = nodes.pop().unwrap();
3978         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
3979         node_b.node.handle_open_channel(&node_a.node.get_our_node_id(), a_flags, &get_event_msg!(node_a, MessageSendEvent::SendOpenChannel, node_b.node.get_our_node_id()));
3980         node_a.node.handle_accept_channel(&node_b.node.get_our_node_id(), b_flags, &get_event_msg!(node_b, MessageSendEvent::SendAcceptChannel, node_a.node.get_our_node_id()));
3981
3982         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
3983
3984         node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
3985         check_added_monitors!(node_a, 0);
3986
3987         node_b.node.handle_funding_created(&node_a.node.get_our_node_id(), &get_event_msg!(node_a, MessageSendEvent::SendFundingCreated, node_b.node.get_our_node_id()));
3988         {
3989                 let mut added_monitors = node_b.chan_monitor.added_monitors.lock().unwrap();
3990                 assert_eq!(added_monitors.len(), 1);
3991                 assert_eq!(added_monitors[0].0, funding_output);
3992                 added_monitors.clear();
3993         }
3994
3995         node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id()));
3996         {
3997                 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
3998                 assert_eq!(added_monitors.len(), 1);
3999                 assert_eq!(added_monitors[0].0, funding_output);
4000                 added_monitors.clear();
4001         }
4002         // Normally, this is where node_a would check for a FundingBroadcastSafe event, but the test de/serializes first instead
4003
4004         nodes.push(node_a);
4005         nodes.push(node_b);
4006
4007         // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4008         let nodes_0_serialized = nodes[0].node.encode();
4009         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4010         nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
4011
4012         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4013         logger = test_utils::TestLogger::new();
4014         new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator);
4015         nodes[0].chan_monitor = &new_chan_monitor;
4016         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4017         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read).unwrap();
4018         assert!(chan_0_monitor_read.is_empty());
4019
4020         let mut nodes_0_read = &nodes_0_serialized[..];
4021         let config = UserConfig::default();
4022         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4023         let (_, nodes_0_deserialized_tmp) = {
4024                 let mut channel_monitors = HashMap::new();
4025                 channel_monitors.insert(chan_0_monitor.get_funding_txo(), &mut chan_0_monitor);
4026                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4027                         default_config: config,
4028                         keys_manager: &keys_manager,
4029                         fee_estimator: &fee_estimator,
4030                         monitor: nodes[0].chan_monitor,
4031                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4032                         logger: &logger,
4033                         channel_monitors: &mut channel_monitors,
4034                 }).unwrap()
4035         };
4036         nodes_0_deserialized = nodes_0_deserialized_tmp;
4037         assert!(nodes_0_read.is_empty());
4038
4039         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4040
4041         assert!(nodes[0].chan_monitor.add_monitor(chan_0_monitor.get_funding_txo(), chan_0_monitor).is_ok());
4042         nodes[0].node = &nodes_0_deserialized;
4043
4044         // After deserializing, make sure the FundingBroadcastSafe event is still held by the channel manager
4045         let events_4 = nodes[0].node.get_and_clear_pending_events();
4046         assert_eq!(events_4.len(), 1);
4047         match events_4[0] {
4048                 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
4049                         assert_eq!(user_channel_id, 42);
4050                         assert_eq!(*funding_txo, funding_output);
4051                 },
4052                 _ => panic!("Unexpected event"),
4053         };
4054
4055         // Make sure the channel is functioning as though the de/serialization never happened
4056         nodes[0].block_notifier.register_listener(nodes[0].node);
4057         assert_eq!(nodes[0].node.list_channels().len(), 1);
4058         check_added_monitors!(nodes[0], 1);
4059
4060         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4061         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4062         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4063         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4064
4065         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4066         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4067         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4068         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4069
4070         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4071         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4072         for node in nodes.iter() {
4073                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4074                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4075                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4076         }
4077
4078         send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4079 }
4080
4081 #[test]
4082 fn test_simple_manager_serialize_deserialize() {
4083         let chanmon_cfgs = create_chanmon_cfgs(2);
4084         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4085         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4086         let logger: test_utils::TestLogger;
4087         let fee_estimator: test_utils::TestFeeEstimator;
4088         let new_chan_monitor: test_utils::TestChannelMonitor;
4089         let keys_manager: test_utils::TestKeysInterface;
4090         let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4091         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4092         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4093
4094         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4095         let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4096
4097         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4098
4099         let nodes_0_serialized = nodes[0].node.encode();
4100         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4101         nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
4102
4103         logger = test_utils::TestLogger::new();
4104         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4105         new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator);
4106         nodes[0].chan_monitor = &new_chan_monitor;
4107         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4108         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read).unwrap();
4109         assert!(chan_0_monitor_read.is_empty());
4110
4111         let mut nodes_0_read = &nodes_0_serialized[..];
4112         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4113         let (_, nodes_0_deserialized_tmp) = {
4114                 let mut channel_monitors = HashMap::new();
4115                 channel_monitors.insert(chan_0_monitor.get_funding_txo(), &mut chan_0_monitor);
4116                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4117                         default_config: UserConfig::default(),
4118                         keys_manager: &keys_manager,
4119                         fee_estimator: &fee_estimator,
4120                         monitor: nodes[0].chan_monitor,
4121                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4122                         logger: &logger,
4123                         channel_monitors: &mut channel_monitors,
4124                 }).unwrap()
4125         };
4126         nodes_0_deserialized = nodes_0_deserialized_tmp;
4127         assert!(nodes_0_read.is_empty());
4128
4129         assert!(nodes[0].chan_monitor.add_monitor(chan_0_monitor.get_funding_txo(), chan_0_monitor).is_ok());
4130         nodes[0].node = &nodes_0_deserialized;
4131         check_added_monitors!(nodes[0], 1);
4132
4133         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4134
4135         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4136         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage, 1_000_000);
4137 }
4138
4139 #[test]
4140 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4141         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4142         let chanmon_cfgs = create_chanmon_cfgs(4);
4143         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4144         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4145         let logger: test_utils::TestLogger;
4146         let fee_estimator: test_utils::TestFeeEstimator;
4147         let new_chan_monitor: test_utils::TestChannelMonitor;
4148         let keys_manager: test_utils::TestKeysInterface;
4149         let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4150         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4151         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4152         create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known());
4153         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4154
4155         let mut node_0_stale_monitors_serialized = Vec::new();
4156         for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
4157                 let mut writer = test_utils::TestVecWriter(Vec::new());
4158                 monitor.1.write_for_disk(&mut writer).unwrap();
4159                 node_0_stale_monitors_serialized.push(writer.0);
4160         }
4161
4162         let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4163
4164         // Serialize the ChannelManager here, but the monitor we keep up-to-date
4165         let nodes_0_serialized = nodes[0].node.encode();
4166
4167         route_payment(&nodes[0], &[&nodes[3]], 1000000);
4168         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4169         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4170         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4171
4172         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4173         // nodes[3])
4174         let mut node_0_monitors_serialized = Vec::new();
4175         for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
4176                 let mut writer = test_utils::TestVecWriter(Vec::new());
4177                 monitor.1.write_for_disk(&mut writer).unwrap();
4178                 node_0_monitors_serialized.push(writer.0);
4179         }
4180
4181         logger = test_utils::TestLogger::new();
4182         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4183         new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator);
4184         nodes[0].chan_monitor = &new_chan_monitor;
4185
4186         let mut node_0_stale_monitors = Vec::new();
4187         for serialized in node_0_stale_monitors_serialized.iter() {
4188                 let mut read = &serialized[..];
4189                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read).unwrap();
4190                 assert!(read.is_empty());
4191                 node_0_stale_monitors.push(monitor);
4192         }
4193
4194         let mut node_0_monitors = Vec::new();
4195         for serialized in node_0_monitors_serialized.iter() {
4196                 let mut read = &serialized[..];
4197                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read).unwrap();
4198                 assert!(read.is_empty());
4199                 node_0_monitors.push(monitor);
4200         }
4201
4202         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4203
4204         let mut nodes_0_read = &nodes_0_serialized[..];
4205         if let Err(msgs::DecodeError::InvalidValue) =
4206                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4207                 default_config: UserConfig::default(),
4208                 keys_manager: &keys_manager,
4209                 fee_estimator: &fee_estimator,
4210                 monitor: nodes[0].chan_monitor,
4211                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4212                 logger: &logger,
4213                 channel_monitors: &mut node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo(), monitor) }).collect(),
4214         }) { } else {
4215                 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4216         };
4217
4218         let mut nodes_0_read = &nodes_0_serialized[..];
4219         let (_, nodes_0_deserialized_tmp) =
4220                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4221                 default_config: UserConfig::default(),
4222                 keys_manager: &keys_manager,
4223                 fee_estimator: &fee_estimator,
4224                 monitor: nodes[0].chan_monitor,
4225                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4226                 logger: &logger,
4227                 channel_monitors: &mut node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo(), monitor) }).collect(),
4228         }).unwrap();
4229         nodes_0_deserialized = nodes_0_deserialized_tmp;
4230         assert!(nodes_0_read.is_empty());
4231
4232         { // Channel close should result in a commitment tx and an HTLC tx
4233                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4234                 assert_eq!(txn.len(), 2);
4235                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4236                 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
4237         }
4238
4239         for monitor in node_0_monitors.drain(..) {
4240                 assert!(nodes[0].chan_monitor.add_monitor(monitor.get_funding_txo(), monitor).is_ok());
4241                 check_added_monitors!(nodes[0], 1);
4242         }
4243         nodes[0].node = &nodes_0_deserialized;
4244
4245         // nodes[1] and nodes[2] have no lost state with nodes[0]...
4246         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4247         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4248         //... and we can even still claim the payment!
4249         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage, 1_000_000);
4250
4251         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4252         let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4253         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4254         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4255         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4256         assert_eq!(msg_events.len(), 1);
4257         if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4258                 match action {
4259                         &ErrorAction::SendErrorMessage { ref msg } => {
4260                                 assert_eq!(msg.channel_id, channel_id);
4261                         },
4262                         _ => panic!("Unexpected event!"),
4263                 }
4264         }
4265 }
4266
4267 macro_rules! check_spendable_outputs {
4268         ($node: expr, $der_idx: expr, $keysinterface: expr, $chan_value: expr) => {
4269                 {
4270                         let events = $node.chan_monitor.simple_monitor.get_and_clear_pending_events();
4271                         let mut txn = Vec::new();
4272                         for event in events {
4273                                 match event {
4274                                         Event::SpendableOutputs { ref outputs } => {
4275                                                 for outp in outputs {
4276                                                         match *outp {
4277                                                                 SpendableOutputDescriptor::StaticOutputRemotePayment { ref outpoint, ref output, ref key_derivation_params } => {
4278                                                                         let input = TxIn {
4279                                                                                 previous_output: outpoint.clone(),
4280                                                                                 script_sig: Script::new(),
4281                                                                                 sequence: 0,
4282                                                                                 witness: Vec::new(),
4283                                                                         };
4284                                                                         let outp = TxOut {
4285                                                                                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4286                                                                                 value: output.value,
4287                                                                         };
4288                                                                         let mut spend_tx = Transaction {
4289                                                                                 version: 2,
4290                                                                                 lock_time: 0,
4291                                                                                 input: vec![input],
4292                                                                                 output: vec![outp],
4293                                                                         };
4294                                                                         let secp_ctx = Secp256k1::new();
4295                                                                         let keys = $keysinterface.derive_channel_keys($chan_value, key_derivation_params.0, key_derivation_params.1);
4296                                                                         let remotepubkey = PublicKey::from_secret_key(&secp_ctx, &keys.payment_key());
4297                                                                         let witness_script = Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: remotepubkey}, Network::Testnet).script_pubkey();
4298                                                                         let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
4299                                                                         let remotesig = secp_ctx.sign(&sighash, &keys.payment_key());
4300                                                                         spend_tx.input[0].witness.push(remotesig.serialize_der().to_vec());
4301                                                                         spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4302                                                                         spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
4303                                                                         txn.push(spend_tx);
4304                                                                 },
4305                                                                 SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref per_commitment_point, ref to_self_delay, ref output, ref key_derivation_params, ref remote_revocation_pubkey } => {
4306                                                                         let input = TxIn {
4307                                                                                 previous_output: outpoint.clone(),
4308                                                                                 script_sig: Script::new(),
4309                                                                                 sequence: *to_self_delay as u32,
4310                                                                                 witness: Vec::new(),
4311                                                                         };
4312                                                                         let outp = TxOut {
4313                                                                                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4314                                                                                 value: output.value,
4315                                                                         };
4316                                                                         let mut spend_tx = Transaction {
4317                                                                                 version: 2,
4318                                                                                 lock_time: 0,
4319                                                                                 input: vec![input],
4320                                                                                 output: vec![outp],
4321                                                                         };
4322                                                                         let secp_ctx = Secp256k1::new();
4323                                                                         let keys = $keysinterface.derive_channel_keys($chan_value, key_derivation_params.0, key_derivation_params.1);
4324                                                                         if let Ok(delayed_payment_key) = chan_utils::derive_private_key(&secp_ctx, &per_commitment_point, keys.delayed_payment_base_key()) {
4325
4326                                                                                 let delayed_payment_pubkey = PublicKey::from_secret_key(&secp_ctx, &delayed_payment_key);
4327                                                                                 let witness_script = chan_utils::get_revokeable_redeemscript(remote_revocation_pubkey, *to_self_delay, &delayed_payment_pubkey);
4328                                                                                 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
4329                                                                                 let local_delayedsig = secp_ctx.sign(&sighash, &delayed_payment_key);
4330                                                                                 spend_tx.input[0].witness.push(local_delayedsig.serialize_der().to_vec());
4331                                                                                 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4332                                                                                 spend_tx.input[0].witness.push(vec!()); //MINIMALIF
4333                                                                                 spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
4334                                                                         } else { panic!() }
4335                                                                         txn.push(spend_tx);
4336                                                                 },
4337                                                                 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
4338                                                                         let secp_ctx = Secp256k1::new();
4339                                                                         let input = TxIn {
4340                                                                                 previous_output: outpoint.clone(),
4341                                                                                 script_sig: Script::new(),
4342                                                                                 sequence: 0,
4343                                                                                 witness: Vec::new(),
4344                                                                         };
4345                                                                         let outp = TxOut {
4346                                                                                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4347                                                                                 value: output.value,
4348                                                                         };
4349                                                                         let mut spend_tx = Transaction {
4350                                                                                 version: 2,
4351                                                                                 lock_time: 0,
4352                                                                                 input: vec![input],
4353                                                                                 output: vec![outp.clone()],
4354                                                                         };
4355                                                                         let secret = {
4356                                                                                 match ExtendedPrivKey::new_master(Network::Testnet, &$node.node_seed) {
4357                                                                                         Ok(master_key) => {
4358                                                                                                 match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx).expect("key space exhausted")) {
4359                                                                                                         Ok(key) => key,
4360                                                                                                         Err(_) => panic!("Your RNG is busted"),
4361                                                                                                 }
4362                                                                                         }
4363                                                                                         Err(_) => panic!("Your rng is busted"),
4364                                                                                 }
4365                                                                         };
4366                                                                         let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
4367                                                                         let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
4368                                                                         let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
4369                                                                         let sig = secp_ctx.sign(&sighash, &secret.private_key.key);
4370                                                                         spend_tx.input[0].witness.push(sig.serialize_der().to_vec());
4371                                                                         spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4372                                                                         spend_tx.input[0].witness.push(pubkey.key.serialize().to_vec());
4373                                                                         txn.push(spend_tx);
4374                                                                 },
4375                                                         }
4376                                                 }
4377                                         },
4378                                         _ => panic!("Unexpected event"),
4379                                 };
4380                         }
4381                         txn
4382                 }
4383         }
4384 }
4385
4386 #[test]
4387 fn test_claim_sizeable_push_msat() {
4388         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4389         let chanmon_cfgs = create_chanmon_cfgs(2);
4390         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4391         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4392         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4393
4394         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4395         nodes[1].node.force_close_channel(&chan.2);
4396         check_closed_broadcast!(nodes[1], false);
4397         check_added_monitors!(nodes[1], 1);
4398         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4399         assert_eq!(node_txn.len(), 1);
4400         check_spends!(node_txn[0], chan.3);
4401         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
4402
4403         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4404         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4405         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4406
4407         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4408         assert_eq!(spend_txn.len(), 1);
4409         check_spends!(spend_txn[0], node_txn[0]);
4410 }
4411
4412 #[test]
4413 fn test_claim_on_remote_sizeable_push_msat() {
4414         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4415         // to_remote output is encumbered by a P2WPKH
4416         let chanmon_cfgs = create_chanmon_cfgs(2);
4417         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4418         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4419         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4420
4421         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4422         nodes[0].node.force_close_channel(&chan.2);
4423         check_closed_broadcast!(nodes[0], false);
4424         check_added_monitors!(nodes[0], 1);
4425
4426         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4427         assert_eq!(node_txn.len(), 1);
4428         check_spends!(node_txn[0], chan.3);
4429         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
4430
4431         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4432         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4433         check_closed_broadcast!(nodes[1], false);
4434         check_added_monitors!(nodes[1], 1);
4435         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4436
4437         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4438         assert_eq!(spend_txn.len(), 2);
4439         assert_eq!(spend_txn[0], spend_txn[1]);
4440         check_spends!(spend_txn[0], node_txn[0]);
4441 }
4442
4443 #[test]
4444 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4445         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4446         // to_remote output is encumbered by a P2WPKH
4447
4448         let chanmon_cfgs = create_chanmon_cfgs(2);
4449         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4450         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4451         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4452
4453         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4454         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4455         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4456         assert_eq!(revoked_local_txn[0].input.len(), 1);
4457         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4458
4459         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4460         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4461         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
4462         check_closed_broadcast!(nodes[1], false);
4463         check_added_monitors!(nodes[1], 1);
4464
4465         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4466         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4467         nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4468         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4469
4470         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4471         assert_eq!(spend_txn.len(), 3);
4472         assert_eq!(spend_txn[0], spend_txn[1]); // to_remote output on revoked remote commitment_tx
4473         check_spends!(spend_txn[0], revoked_local_txn[0]);
4474         check_spends!(spend_txn[2], node_txn[0]);
4475 }
4476
4477 #[test]
4478 fn test_static_spendable_outputs_preimage_tx() {
4479         let chanmon_cfgs = create_chanmon_cfgs(2);
4480         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4481         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4482         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4483
4484         // Create some initial channels
4485         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4486
4487         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4488
4489         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4490         assert_eq!(commitment_tx[0].input.len(), 1);
4491         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4492
4493         // Settle A's commitment tx on B's chain
4494         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4495         assert!(nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000));
4496         check_added_monitors!(nodes[1], 1);
4497         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
4498         check_added_monitors!(nodes[1], 1);
4499         let events = nodes[1].node.get_and_clear_pending_msg_events();
4500         match events[0] {
4501                 MessageSendEvent::UpdateHTLCs { .. } => {},
4502                 _ => panic!("Unexpected event"),
4503         }
4504         match events[1] {
4505                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4506                 _ => panic!("Unexepected event"),
4507         }
4508
4509         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4510         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4511         assert_eq!(node_txn.len(), 3);
4512         check_spends!(node_txn[0], commitment_tx[0]);
4513         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4514         check_spends!(node_txn[1], chan_1.3);
4515         check_spends!(node_txn[2], node_txn[1]);
4516
4517         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4518         nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4519         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4520
4521         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4522         assert_eq!(spend_txn.len(), 1);
4523         check_spends!(spend_txn[0], node_txn[0]);
4524 }
4525
4526 #[test]
4527 fn test_static_spendable_outputs_timeout_tx() {
4528         let chanmon_cfgs = create_chanmon_cfgs(2);
4529         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4530         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4531         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4532
4533         // Create some initial channels
4534         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4535
4536         // Rebalance the network a bit by relaying one payment through all the channels ...
4537         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
4538
4539         let (_, our_payment_hash) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4540
4541         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4542         assert_eq!(commitment_tx[0].input.len(), 1);
4543         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4544
4545         // Settle A's commitment tx on B' chain
4546         let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
4547         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 0);
4548         check_added_monitors!(nodes[1], 1);
4549         let events = nodes[1].node.get_and_clear_pending_msg_events();
4550         match events[0] {
4551                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4552                 _ => panic!("Unexpected event"),
4553         }
4554
4555         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4556         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4557         assert_eq!(node_txn.len(), 3); // ChannelManager : 2 (local commitent tx + HTLC-timeout), ChannelMonitor: timeout tx
4558         check_spends!(node_txn[0],  commitment_tx[0].clone());
4559         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4560         check_spends!(node_txn[1], chan_1.3.clone());
4561         check_spends!(node_txn[2], node_txn[1]);
4562
4563         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4564         nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4565         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4566         expect_payment_failed!(nodes[1], our_payment_hash, true);
4567
4568         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4569         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote (*2), timeout_tx.output (*1)
4570         check_spends!(spend_txn[2], node_txn[0].clone());
4571 }
4572
4573 #[test]
4574 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4575         let chanmon_cfgs = create_chanmon_cfgs(2);
4576         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4577         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4578         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4579
4580         // Create some initial channels
4581         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4582
4583         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4584         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4585         assert_eq!(revoked_local_txn[0].input.len(), 1);
4586         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4587
4588         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4589
4590         let  header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4591         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
4592         check_closed_broadcast!(nodes[1], false);
4593         check_added_monitors!(nodes[1], 1);
4594
4595         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4596         assert_eq!(node_txn.len(), 2);
4597         assert_eq!(node_txn[0].input.len(), 2);
4598         check_spends!(node_txn[0], revoked_local_txn[0]);
4599
4600         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4601         nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4602         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4603
4604         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4605         assert_eq!(spend_txn.len(), 1);
4606         check_spends!(spend_txn[0], node_txn[0]);
4607 }
4608
4609 #[test]
4610 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4611         let chanmon_cfgs = create_chanmon_cfgs(2);
4612         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4613         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4614         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4615
4616         // Create some initial channels
4617         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4618
4619         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4620         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4621         assert_eq!(revoked_local_txn[0].input.len(), 1);
4622         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4623
4624         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4625
4626         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4627         // A will generate HTLC-Timeout from revoked commitment tx
4628         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4629         check_closed_broadcast!(nodes[0], false);
4630         check_added_monitors!(nodes[0], 1);
4631
4632         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4633         assert_eq!(revoked_htlc_txn.len(), 2);
4634         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4635         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4636         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4637         check_spends!(revoked_htlc_txn[1], chan_1.3);
4638
4639         // B will generate justice tx from A's revoked commitment/HTLC tx
4640         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 0);
4641         check_closed_broadcast!(nodes[1], false);
4642         check_added_monitors!(nodes[1], 1);
4643
4644         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4645         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
4646         assert_eq!(node_txn[0].input.len(), 2);
4647         check_spends!(node_txn[0], revoked_local_txn[0]);
4648         check_spends!(node_txn[1], chan_1.3);
4649         assert_eq!(node_txn[2].input.len(), 1);
4650         check_spends!(node_txn[2], revoked_htlc_txn[0]);
4651         assert_eq!(node_txn[3].input.len(), 1);
4652         check_spends!(node_txn[3], revoked_local_txn[0]);
4653
4654         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4655         nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone(), node_txn[2].clone()] }, 1);
4656         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4657
4658         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4659         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4660         assert_eq!(spend_txn.len(), 2);
4661         check_spends!(spend_txn[0], node_txn[0]);
4662         check_spends!(spend_txn[1], node_txn[2]);
4663 }
4664
4665 #[test]
4666 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4667         let chanmon_cfgs = create_chanmon_cfgs(2);
4668         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4669         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4670         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4671
4672         // Create some initial channels
4673         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4674
4675         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4676         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4677         assert_eq!(revoked_local_txn[0].input.len(), 1);
4678         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4679
4680         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4681
4682         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4683         // B will generate HTLC-Success from revoked commitment tx
4684         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4685         check_closed_broadcast!(nodes[1], false);
4686         check_added_monitors!(nodes[1], 1);
4687         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4688
4689         assert_eq!(revoked_htlc_txn.len(), 2);
4690         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4691         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4692         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4693
4694         // A will generate justice tx from B's revoked commitment/HTLC tx
4695         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
4696         check_closed_broadcast!(nodes[0], false);
4697         check_added_monitors!(nodes[0], 1);
4698
4699         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4700         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
4701         assert_eq!(node_txn[2].input.len(), 1);
4702         check_spends!(node_txn[2], revoked_htlc_txn[0]);
4703
4704         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4705         nodes[0].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone(), node_txn[2].clone()] }, 1);
4706         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4707
4708         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4709         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
4710         assert_eq!(spend_txn.len(), 5); // Duplicated SpendableOutput due to block rescan after revoked htlc output tracking
4711         assert_eq!(spend_txn[0], spend_txn[1]);
4712         assert_eq!(spend_txn[0], spend_txn[2]);
4713         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4714         check_spends!(spend_txn[3], node_txn[0]); // spending justice tx output from revoked local tx htlc received output
4715         check_spends!(spend_txn[4], node_txn[2]); // spending justice tx output on htlc success tx
4716 }
4717
4718 #[test]
4719 fn test_onchain_to_onchain_claim() {
4720         // Test that in case of channel closure, we detect the state of output thanks to
4721         // ChainWatchInterface and claim HTLC on downstream peer's remote commitment tx.
4722         // First, have C claim an HTLC against its own latest commitment transaction.
4723         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4724         // channel.
4725         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4726         // gets broadcast.
4727
4728         let chanmon_cfgs = create_chanmon_cfgs(3);
4729         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4730         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4731         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4732
4733         // Create some initial channels
4734         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4735         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4736
4737         // Rebalance the network a bit by relaying one payment through all the channels ...
4738         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
4739         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
4740
4741         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
4742         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
4743         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4744         check_spends!(commitment_tx[0], chan_2.3);
4745         nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000);
4746         check_added_monitors!(nodes[2], 1);
4747         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4748         assert!(updates.update_add_htlcs.is_empty());
4749         assert!(updates.update_fail_htlcs.is_empty());
4750         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4751         assert!(updates.update_fail_malformed_htlcs.is_empty());
4752
4753         nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
4754         check_closed_broadcast!(nodes[2], false);
4755         check_added_monitors!(nodes[2], 1);
4756
4757         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
4758         assert_eq!(c_txn.len(), 3);
4759         assert_eq!(c_txn[0], c_txn[2]);
4760         assert_eq!(commitment_tx[0], c_txn[1]);
4761         check_spends!(c_txn[1], chan_2.3);
4762         check_spends!(c_txn[2], c_txn[1]);
4763         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
4764         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4765         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4766         assert_eq!(c_txn[0].lock_time, 0); // Success tx
4767
4768         // 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
4769         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
4770         {
4771                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4772                 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-timeout tx
4773                 assert_eq!(b_txn.len(), 3);
4774                 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
4775                 check_spends!(b_txn[2], b_txn[1]); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
4776                 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4777                 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4778                 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
4779                 check_spends!(b_txn[0], c_txn[1]); // timeout tx on C remote commitment tx, issued by ChannelMonitor, * 2 due to block rescan
4780                 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4781                 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4782                 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
4783                 b_txn.clear();
4784         }
4785         check_added_monitors!(nodes[1], 1);
4786         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4787         check_added_monitors!(nodes[1], 1);
4788         match msg_events[0] {
4789                 MessageSendEvent::BroadcastChannelUpdate {  .. } => {},
4790                 _ => panic!("Unexpected event"),
4791         }
4792         match msg_events[1] {
4793                 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, .. } } => {
4794                         assert!(update_add_htlcs.is_empty());
4795                         assert!(update_fail_htlcs.is_empty());
4796                         assert_eq!(update_fulfill_htlcs.len(), 1);
4797                         assert!(update_fail_malformed_htlcs.is_empty());
4798                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4799                 },
4800                 _ => panic!("Unexpected event"),
4801         };
4802         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4803         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4804         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
4805         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4806         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
4807         assert_eq!(b_txn.len(), 3);
4808         check_spends!(b_txn[1], chan_1.3);
4809         check_spends!(b_txn[2], b_txn[1]);
4810         check_spends!(b_txn[0], commitment_tx[0]);
4811         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4812         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4813         assert_eq!(b_txn[0].lock_time, 0); // Success tx
4814
4815         check_closed_broadcast!(nodes[1], false);
4816         check_added_monitors!(nodes[1], 1);
4817 }
4818
4819 #[test]
4820 fn test_duplicate_payment_hash_one_failure_one_success() {
4821         // Topology : A --> B --> C
4822         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4823         let chanmon_cfgs = create_chanmon_cfgs(3);
4824         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4825         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4826         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4827
4828         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4829         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4830
4831         let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
4832         *nodes[0].network_payment_count.borrow_mut() -= 1;
4833         assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
4834
4835         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4836         assert_eq!(commitment_txn[0].input.len(), 1);
4837         check_spends!(commitment_txn[0], chan_2.3);
4838
4839         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4840         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
4841         check_closed_broadcast!(nodes[1], false);
4842         check_added_monitors!(nodes[1], 1);
4843
4844         let htlc_timeout_tx;
4845         { // Extract one of the two HTLC-Timeout transaction
4846                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4847                 // ChannelMonitor: timeout tx * 2, ChannelManager: local commitment tx + HTLC-timeout * 2
4848                 assert_eq!(node_txn.len(), 5);
4849                 check_spends!(node_txn[0], commitment_txn[0]);
4850                 assert_eq!(node_txn[0].input.len(), 1);
4851                 check_spends!(node_txn[1], commitment_txn[0]);
4852                 assert_eq!(node_txn[1].input.len(), 1);
4853                 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
4854                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4855                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4856                 check_spends!(node_txn[2], chan_2.3);
4857                 check_spends!(node_txn[3], node_txn[2]);
4858                 check_spends!(node_txn[4], node_txn[2]);
4859                 htlc_timeout_tx = node_txn[1].clone();
4860         }
4861
4862         nodes[2].node.claim_funds(our_payment_preimage, &None, 900_000);
4863         nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
4864         check_added_monitors!(nodes[2], 3);
4865         let events = nodes[2].node.get_and_clear_pending_msg_events();
4866         match events[0] {
4867                 MessageSendEvent::UpdateHTLCs { .. } => {},
4868                 _ => panic!("Unexpected event"),
4869         }
4870         match events[1] {
4871                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4872                 _ => panic!("Unexepected event"),
4873         }
4874         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4875         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)
4876         check_spends!(htlc_success_txn[2], chan_2.3);
4877         check_spends!(htlc_success_txn[3], htlc_success_txn[2]);
4878         check_spends!(htlc_success_txn[4], htlc_success_txn[2]);
4879         assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
4880         assert_eq!(htlc_success_txn[0].input.len(), 1);
4881         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4882         assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
4883         assert_eq!(htlc_success_txn[1].input.len(), 1);
4884         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4885         assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
4886         check_spends!(htlc_success_txn[0], commitment_txn[0]);
4887         check_spends!(htlc_success_txn[1], commitment_txn[0]);
4888
4889         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![htlc_timeout_tx] }, 200);
4890         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 200, true, header.bitcoin_hash());
4891         expect_pending_htlcs_forwardable!(nodes[1]);
4892         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4893         assert!(htlc_updates.update_add_htlcs.is_empty());
4894         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4895         assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
4896         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4897         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4898         check_added_monitors!(nodes[1], 1);
4899
4900         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4901         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4902         {
4903                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4904                 let events = nodes[0].node.get_and_clear_pending_msg_events();
4905                 assert_eq!(events.len(), 1);
4906                 match events[0] {
4907                         MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. }  } => {
4908                         },
4909                         _ => { panic!("Unexpected event"); }
4910                 }
4911         }
4912         expect_payment_failed!(nodes[0], duplicate_payment_hash, false);
4913
4914         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4915         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
4916         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4917         assert!(updates.update_add_htlcs.is_empty());
4918         assert!(updates.update_fail_htlcs.is_empty());
4919         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4920         assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
4921         assert!(updates.update_fail_malformed_htlcs.is_empty());
4922         check_added_monitors!(nodes[1], 1);
4923
4924         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4925         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4926
4927         let events = nodes[0].node.get_and_clear_pending_events();
4928         match events[0] {
4929                 Event::PaymentSent { ref payment_preimage } => {
4930                         assert_eq!(*payment_preimage, our_payment_preimage);
4931                 }
4932                 _ => panic!("Unexpected event"),
4933         }
4934 }
4935
4936 #[test]
4937 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4938         let chanmon_cfgs = create_chanmon_cfgs(2);
4939         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4940         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4941         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4942
4943         // Create some initial channels
4944         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4945
4946         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
4947         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4948         assert_eq!(local_txn[0].input.len(), 1);
4949         check_spends!(local_txn[0], chan_1.3);
4950
4951         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4952         nodes[1].node.claim_funds(payment_preimage, &None, 9_000_000);
4953         check_added_monitors!(nodes[1], 1);
4954         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4955         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![local_txn[0].clone()] }, 1);
4956         check_added_monitors!(nodes[1], 1);
4957         let events = nodes[1].node.get_and_clear_pending_msg_events();
4958         match events[0] {
4959                 MessageSendEvent::UpdateHTLCs { .. } => {},
4960                 _ => panic!("Unexpected event"),
4961         }
4962         match events[1] {
4963                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4964                 _ => panic!("Unexepected event"),
4965         }
4966         let node_txn = {
4967                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4968                 assert_eq!(node_txn[0].input.len(), 1);
4969                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4970                 check_spends!(node_txn[0], local_txn[0]);
4971                 vec![node_txn[0].clone(), node_txn[2].clone()]
4972         };
4973
4974         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4975         nodes[1].block_notifier.block_connected(&Block { header: header_201, txdata: node_txn.clone() }, 201);
4976         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 201, true, header_201.bitcoin_hash());
4977
4978         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4979         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4980         assert_eq!(spend_txn.len(), 2);
4981         check_spends!(spend_txn[0], node_txn[0]);
4982         check_spends!(spend_txn[1], node_txn[1]);
4983 }
4984
4985 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4986         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4987         // unrevoked commitment transaction.
4988         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4989         // a remote RAA before they could be failed backwards (and combinations thereof).
4990         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4991         // use the same payment hashes.
4992         // Thus, we use a six-node network:
4993         //
4994         // A \         / E
4995         //    - C - D -
4996         // B /         \ F
4997         // And test where C fails back to A/B when D announces its latest commitment transaction
4998         let chanmon_cfgs = create_chanmon_cfgs(6);
4999         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5000         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
5001         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5002         let logger = test_utils::TestLogger::new();
5003
5004         create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5005         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5006         let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5007         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5008         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5009
5010         // Rebalance and check output sanity...
5011         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000, 500_000);
5012         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000, 500_000);
5013         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5014
5015         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
5016         // 0th HTLC:
5017         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
5018         // 1st HTLC:
5019         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
5020         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
5021         let our_node_id = &nodes[1].node.get_our_node_id();
5022         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).unwrap();
5023         // 2nd HTLC:
5024         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
5025         // 3rd HTLC:
5026         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
5027         // 4th HTLC:
5028         let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5029         // 5th HTLC:
5030         let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5031         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).unwrap();
5032         // 6th HTLC:
5033         send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
5034         // 7th HTLC:
5035         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
5036
5037         // 8th HTLC:
5038         let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5039         // 9th HTLC:
5040         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).unwrap();
5041         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
5042
5043         // 10th HTLC:
5044         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
5045         // 11th HTLC:
5046         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).unwrap();
5047         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
5048
5049         // Double-check that six of the new HTLC were added
5050         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5051         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5052         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5053         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5054
5055         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5056         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5057         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1, &None));
5058         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3, &None));
5059         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5, &None));
5060         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6, &None));
5061         check_added_monitors!(nodes[4], 0);
5062         expect_pending_htlcs_forwardable!(nodes[4]);
5063         check_added_monitors!(nodes[4], 1);
5064
5065         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5066         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5067         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5068         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5069         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5070         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5071
5072         // Fail 3rd below-dust and 7th above-dust HTLCs
5073         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2, &None));
5074         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4, &None));
5075         check_added_monitors!(nodes[5], 0);
5076         expect_pending_htlcs_forwardable!(nodes[5]);
5077         check_added_monitors!(nodes[5], 1);
5078
5079         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5080         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5081         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5082         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5083
5084         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5085
5086         expect_pending_htlcs_forwardable!(nodes[3]);
5087         check_added_monitors!(nodes[3], 1);
5088         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5089         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5090         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5091         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5092         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5093         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5094         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5095         if deliver_last_raa {
5096                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5097         } else {
5098                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5099         }
5100
5101         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5102         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5103         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5104         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5105         //
5106         // We now broadcast the latest commitment transaction, which *should* result in failures for
5107         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5108         // the non-broadcast above-dust HTLCs.
5109         //
5110         // Alternatively, we may broadcast the previous commitment transaction, which should only
5111         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5112         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5113
5114         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5115         if announce_latest {
5116                 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![ds_last_commitment_tx[0].clone()]}, 1);
5117         } else {
5118                 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![ds_prev_commitment_tx[0].clone()]}, 1);
5119         }
5120         connect_blocks(&nodes[2].block_notifier, ANTI_REORG_DELAY - 1, 1, true,  header.bitcoin_hash());
5121         check_closed_broadcast!(nodes[2], false);
5122         expect_pending_htlcs_forwardable!(nodes[2]);
5123         check_added_monitors!(nodes[2], 3);
5124
5125         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5126         assert_eq!(cs_msgs.len(), 2);
5127         let mut a_done = false;
5128         for msg in cs_msgs {
5129                 match msg {
5130                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5131                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5132                                 // should be failed-backwards here.
5133                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5134                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5135                                         for htlc in &updates.update_fail_htlcs {
5136                                                 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 });
5137                                         }
5138                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5139                                         assert!(!a_done);
5140                                         a_done = true;
5141                                         &nodes[0]
5142                                 } else {
5143                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5144                                         for htlc in &updates.update_fail_htlcs {
5145                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5146                                         }
5147                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5148                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5149                                         &nodes[1]
5150                                 };
5151                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5152                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5153                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5154                                 if announce_latest {
5155                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5156                                         if *node_id == nodes[0].node.get_our_node_id() {
5157                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5158                                         }
5159                                 }
5160                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5161                         },
5162                         _ => panic!("Unexpected event"),
5163                 }
5164         }
5165
5166         let as_events = nodes[0].node.get_and_clear_pending_events();
5167         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5168         let mut as_failds = HashSet::new();
5169         for event in as_events.iter() {
5170                 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5171                         assert!(as_failds.insert(*payment_hash));
5172                         if *payment_hash != payment_hash_2 {
5173                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5174                         } else {
5175                                 assert!(!rejected_by_dest);
5176                         }
5177                 } else { panic!("Unexpected event"); }
5178         }
5179         assert!(as_failds.contains(&payment_hash_1));
5180         assert!(as_failds.contains(&payment_hash_2));
5181         if announce_latest {
5182                 assert!(as_failds.contains(&payment_hash_3));
5183                 assert!(as_failds.contains(&payment_hash_5));
5184         }
5185         assert!(as_failds.contains(&payment_hash_6));
5186
5187         let bs_events = nodes[1].node.get_and_clear_pending_events();
5188         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5189         let mut bs_failds = HashSet::new();
5190         for event in bs_events.iter() {
5191                 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5192                         assert!(bs_failds.insert(*payment_hash));
5193                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5194                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5195                         } else {
5196                                 assert!(!rejected_by_dest);
5197                         }
5198                 } else { panic!("Unexpected event"); }
5199         }
5200         assert!(bs_failds.contains(&payment_hash_1));
5201         assert!(bs_failds.contains(&payment_hash_2));
5202         if announce_latest {
5203                 assert!(bs_failds.contains(&payment_hash_4));
5204         }
5205         assert!(bs_failds.contains(&payment_hash_5));
5206
5207         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5208         // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
5209         // to unknown-preimage-etc, B should have gotten 2. Thus, in the
5210         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
5211         // PaymentFailureNetworkUpdates.
5212         let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
5213         assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5214         let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5215         assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5216         for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
5217                 match event {
5218                         &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
5219                         _ => panic!("Unexpected event"),
5220                 }
5221         }
5222 }
5223
5224 #[test]
5225 fn test_fail_backwards_latest_remote_announce_a() {
5226         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5227 }
5228
5229 #[test]
5230 fn test_fail_backwards_latest_remote_announce_b() {
5231         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5232 }
5233
5234 #[test]
5235 fn test_fail_backwards_previous_remote_announce() {
5236         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5237         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5238         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5239 }
5240
5241 #[test]
5242 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5243         let chanmon_cfgs = create_chanmon_cfgs(2);
5244         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5245         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5246         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5247
5248         // Create some initial channels
5249         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5250
5251         let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5252         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5253         assert_eq!(local_txn[0].input.len(), 1);
5254         check_spends!(local_txn[0], chan_1.3);
5255
5256         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5257         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5258         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![local_txn[0].clone()] }, 200);
5259         check_closed_broadcast!(nodes[0], false);
5260         check_added_monitors!(nodes[0], 1);
5261
5262         let htlc_timeout = {
5263                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5264                 assert_eq!(node_txn[0].input.len(), 1);
5265                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5266                 check_spends!(node_txn[0], local_txn[0]);
5267                 node_txn[0].clone()
5268         };
5269
5270         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5271         nodes[0].block_notifier.block_connected(&Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
5272         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 201, true, header_201.bitcoin_hash());
5273         expect_payment_failed!(nodes[0], our_payment_hash, true);
5274
5275         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5276         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5277         assert_eq!(spend_txn.len(), 3);
5278         assert_eq!(spend_txn[0], spend_txn[1]);
5279         check_spends!(spend_txn[0], local_txn[0]);
5280         check_spends!(spend_txn[2], htlc_timeout);
5281 }
5282
5283 #[test]
5284 fn test_key_derivation_params() {
5285         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5286         // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5287         // let us re-derive the channel key set to then derive a delayed_payment_key.
5288
5289         let chanmon_cfgs = create_chanmon_cfgs(3);
5290
5291         // We manually create the node configuration to backup the seed.
5292         let mut rng = thread_rng();
5293         let mut seed = [0; 32];
5294         rng.fill_bytes(&mut seed);
5295         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5296         let chan_monitor = test_utils::TestChannelMonitor::new(&chanmon_cfgs[0].chain_monitor, &chanmon_cfgs[0].tx_broadcaster, &chanmon_cfgs[0].logger, &chanmon_cfgs[0].fee_estimator);
5297         let node = NodeCfg { chain_monitor: &chanmon_cfgs[0].chain_monitor, logger: &chanmon_cfgs[0].logger, tx_broadcaster: &chanmon_cfgs[0].tx_broadcaster, fee_estimator: &chanmon_cfgs[0].fee_estimator, chan_monitor, keys_manager, node_seed: seed };
5298         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5299         node_cfgs.remove(0);
5300         node_cfgs.insert(0, node);
5301
5302         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5303         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5304
5305         // Create some initial channels
5306         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5307         // for node 0
5308         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5309         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5310         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5311
5312         let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5313         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5314         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5315         assert_eq!(local_txn_1[0].input.len(), 1);
5316         check_spends!(local_txn_1[0], chan_1.3);
5317
5318         // We check funding pubkey are unique
5319         let (from_0_funding_key_0, from_0_funding_key_1) = (PublicKey::from_slice(&local_txn_0[0].input[0].witness[3][2..35]), PublicKey::from_slice(&local_txn_0[0].input[0].witness[3][36..69]));
5320         let (from_1_funding_key_0, from_1_funding_key_1) = (PublicKey::from_slice(&local_txn_1[0].input[0].witness[3][2..35]), PublicKey::from_slice(&local_txn_1[0].input[0].witness[3][36..69]));
5321         if from_0_funding_key_0 == from_1_funding_key_0
5322             || from_0_funding_key_0 == from_1_funding_key_1
5323             || from_0_funding_key_1 == from_1_funding_key_0
5324             || from_0_funding_key_1 == from_1_funding_key_1 {
5325                 panic!("Funding pubkeys aren't unique");
5326         }
5327
5328         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5329         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5330         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![local_txn_1[0].clone()] }, 200);
5331         check_closed_broadcast!(nodes[0], false);
5332         check_added_monitors!(nodes[0], 1);
5333
5334         let htlc_timeout = {
5335                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5336                 assert_eq!(node_txn[0].input.len(), 1);
5337                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5338                 check_spends!(node_txn[0], local_txn_1[0]);
5339                 node_txn[0].clone()
5340         };
5341
5342         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5343         nodes[0].block_notifier.block_connected(&Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
5344         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 201, true, header_201.bitcoin_hash());
5345         expect_payment_failed!(nodes[0], our_payment_hash, true);
5346
5347         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5348         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5349         let spend_txn = check_spendable_outputs!(nodes[0], 1, new_keys_manager, 100000);
5350         assert_eq!(spend_txn.len(), 3);
5351         assert_eq!(spend_txn[0], spend_txn[1]);
5352         check_spends!(spend_txn[0], local_txn_1[0]);
5353         check_spends!(spend_txn[2], htlc_timeout);
5354 }
5355
5356 #[test]
5357 fn test_static_output_closing_tx() {
5358         let chanmon_cfgs = create_chanmon_cfgs(2);
5359         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5360         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5361         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5362
5363         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5364
5365         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
5366         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5367
5368         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5369         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![closing_tx.clone()] }, 0);
5370         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 0, true, header.bitcoin_hash());
5371
5372         let spend_txn = check_spendable_outputs!(nodes[0], 2, node_cfgs[0].keys_manager, 100000);
5373         assert_eq!(spend_txn.len(), 1);
5374         check_spends!(spend_txn[0], closing_tx);
5375
5376         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![closing_tx.clone()] }, 0);
5377         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 0, true, header.bitcoin_hash());
5378
5379         let spend_txn = check_spendable_outputs!(nodes[1], 2, node_cfgs[1].keys_manager, 100000);
5380         assert_eq!(spend_txn.len(), 1);
5381         check_spends!(spend_txn[0], closing_tx);
5382 }
5383
5384 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5385         let chanmon_cfgs = create_chanmon_cfgs(2);
5386         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5387         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5388         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5389         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5390
5391         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5392
5393         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5394         // present in B's local commitment transaction, but none of A's commitment transactions.
5395         assert!(nodes[1].node.claim_funds(our_payment_preimage, &None, if use_dust { 50_000 } else { 3_000_000 }));
5396         check_added_monitors!(nodes[1], 1);
5397
5398         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5399         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5400         let events = nodes[0].node.get_and_clear_pending_events();
5401         assert_eq!(events.len(), 1);
5402         match events[0] {
5403                 Event::PaymentSent { payment_preimage } => {
5404                         assert_eq!(payment_preimage, our_payment_preimage);
5405                 },
5406                 _ => panic!("Unexpected event"),
5407         }
5408
5409         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5410         check_added_monitors!(nodes[0], 1);
5411         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5412         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5413         check_added_monitors!(nodes[1], 1);
5414
5415         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5416         for i in 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + CHAN_CONFIRM_DEPTH + 1 {
5417                 nodes[1].block_notifier.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
5418                 header.prev_blockhash = header.bitcoin_hash();
5419         }
5420         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5421         check_closed_broadcast!(nodes[1], false);
5422         check_added_monitors!(nodes[1], 1);
5423 }
5424
5425 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5426         let chanmon_cfgs = create_chanmon_cfgs(2);
5427         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5428         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5429         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5430         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5431         let logger = test_utils::TestLogger::new();
5432
5433         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5434         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5435         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).unwrap();
5436         nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
5437         check_added_monitors!(nodes[0], 1);
5438
5439         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5440
5441         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5442         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5443         // to "time out" the HTLC.
5444
5445         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5446
5447         for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5448                 nodes[0].block_notifier.block_connected(&Block { header, txdata: Vec::new()}, i);
5449                 header.prev_blockhash = header.bitcoin_hash();
5450         }
5451         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5452         check_closed_broadcast!(nodes[0], false);
5453         check_added_monitors!(nodes[0], 1);
5454 }
5455
5456 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5457         let chanmon_cfgs = create_chanmon_cfgs(3);
5458         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5459         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5460         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5461         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5462
5463         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5464         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5465         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5466         // actually revoked.
5467         let htlc_value = if use_dust { 50000 } else { 3000000 };
5468         let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5469         assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash, &None));
5470         expect_pending_htlcs_forwardable!(nodes[1]);
5471         check_added_monitors!(nodes[1], 1);
5472
5473         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5474         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5475         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5476         check_added_monitors!(nodes[0], 1);
5477         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5478         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5479         check_added_monitors!(nodes[1], 1);
5480         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5481         check_added_monitors!(nodes[1], 1);
5482         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5483
5484         if check_revoke_no_close {
5485                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5486                 check_added_monitors!(nodes[0], 1);
5487         }
5488
5489         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5490         for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5491                 nodes[0].block_notifier.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
5492                 header.prev_blockhash = header.bitcoin_hash();
5493         }
5494         if !check_revoke_no_close {
5495                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5496                 check_closed_broadcast!(nodes[0], false);
5497                 check_added_monitors!(nodes[0], 1);
5498         } else {
5499                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5500         }
5501 }
5502
5503 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5504 // There are only a few cases to test here:
5505 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5506 //    broadcastable commitment transactions result in channel closure,
5507 //  * its included in an unrevoked-but-previous remote commitment transaction,
5508 //  * its included in the latest remote or local commitment transactions.
5509 // We test each of the three possible commitment transactions individually and use both dust and
5510 // non-dust HTLCs.
5511 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5512 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5513 // tested for at least one of the cases in other tests.
5514 #[test]
5515 fn htlc_claim_single_commitment_only_a() {
5516         do_htlc_claim_local_commitment_only(true);
5517         do_htlc_claim_local_commitment_only(false);
5518
5519         do_htlc_claim_current_remote_commitment_only(true);
5520         do_htlc_claim_current_remote_commitment_only(false);
5521 }
5522
5523 #[test]
5524 fn htlc_claim_single_commitment_only_b() {
5525         do_htlc_claim_previous_remote_commitment_only(true, false);
5526         do_htlc_claim_previous_remote_commitment_only(false, false);
5527         do_htlc_claim_previous_remote_commitment_only(true, true);
5528         do_htlc_claim_previous_remote_commitment_only(false, true);
5529 }
5530
5531 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>)
5532         where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
5533                                 F2: FnMut(),
5534 {
5535         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);
5536 }
5537
5538 // test_case
5539 // 0: node1 fails backward
5540 // 1: final node fails backward
5541 // 2: payment completed but the user rejects the payment
5542 // 3: final node fails backward (but tamper onion payloads from node0)
5543 // 100: trigger error in the intermediate node and tamper returning fail_htlc
5544 // 200: trigger error in the final node and tamper returning fail_htlc
5545 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>)
5546         where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
5547                                 F2: for <'a> FnMut(&'a mut msgs::UpdateFailHTLC),
5548                                 F3: FnMut(),
5549 {
5550
5551         // reset block height
5552         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5553         for ix in 0..nodes.len() {
5554                 nodes[ix].block_notifier.block_connected_checked(&header, 1, &[], &[]);
5555         }
5556
5557         macro_rules! expect_event {
5558                 ($node: expr, $event_type: path) => {{
5559                         let events = $node.node.get_and_clear_pending_events();
5560                         assert_eq!(events.len(), 1);
5561                         match events[0] {
5562                                 $event_type { .. } => {},
5563                                 _ => panic!("Unexpected event"),
5564                         }
5565                 }}
5566         }
5567
5568         macro_rules! expect_htlc_forward {
5569                 ($node: expr) => {{
5570                         expect_event!($node, Event::PendingHTLCsForwardable);
5571                         $node.node.process_pending_htlc_forwards();
5572                 }}
5573         }
5574
5575         // 0 ~~> 2 send payment
5576         nodes[0].node.send_payment(&route, payment_hash.clone(), &None).unwrap();
5577         check_added_monitors!(nodes[0], 1);
5578         let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5579         // temper update_add (0 => 1)
5580         let mut update_add_0 = update_0.update_add_htlcs[0].clone();
5581         if test_case == 0 || test_case == 3 || test_case == 100 {
5582                 callback_msg(&mut update_add_0);
5583                 callback_node();
5584         }
5585         // 0 => 1 update_add & CS
5586         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_0);
5587         commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
5588
5589         let update_1_0 = match test_case {
5590                 0|100 => { // intermediate node failure; fail backward to 0
5591                         let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5592                         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));
5593                         update_1_0
5594                 },
5595                 1|2|3|200 => { // final node failure; forwarding to 2
5596                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5597                         // forwarding on 1
5598                         if test_case != 200 {
5599                                 callback_node();
5600                         }
5601                         expect_htlc_forward!(&nodes[1]);
5602
5603                         let update_1 = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
5604                         check_added_monitors!(&nodes[1], 1);
5605                         assert_eq!(update_1.update_add_htlcs.len(), 1);
5606                         // tamper update_add (1 => 2)
5607                         let mut update_add_1 = update_1.update_add_htlcs[0].clone();
5608                         if test_case != 3 && test_case != 200 {
5609                                 callback_msg(&mut update_add_1);
5610                         }
5611
5612                         // 1 => 2
5613                         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_1);
5614                         commitment_signed_dance!(nodes[2], nodes[1], update_1.commitment_signed, false, true);
5615
5616                         if test_case == 2 || test_case == 200 {
5617                                 expect_htlc_forward!(&nodes[2]);
5618                                 expect_event!(&nodes[2], Event::PaymentReceived);
5619                                 callback_node();
5620                                 expect_pending_htlcs_forwardable!(nodes[2]);
5621                         }
5622
5623                         let update_2_1 = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5624                         if test_case == 2 || test_case == 200 {
5625                                 check_added_monitors!(&nodes[2], 1);
5626                         }
5627                         assert!(update_2_1.update_fail_htlcs.len() == 1);
5628
5629                         let mut fail_msg = update_2_1.update_fail_htlcs[0].clone();
5630                         if test_case == 200 {
5631                                 callback_fail(&mut fail_msg);
5632                         }
5633
5634                         // 2 => 1
5635                         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_msg);
5636                         commitment_signed_dance!(nodes[1], nodes[2], update_2_1.commitment_signed, true);
5637
5638                         // backward fail on 1
5639                         let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5640                         assert!(update_1_0.update_fail_htlcs.len() == 1);
5641                         update_1_0
5642                 },
5643                 _ => unreachable!(),
5644         };
5645
5646         // 1 => 0 commitment_signed_dance
5647         if update_1_0.update_fail_htlcs.len() > 0 {
5648                 let mut fail_msg = update_1_0.update_fail_htlcs[0].clone();
5649                 if test_case == 100 {
5650                         callback_fail(&mut fail_msg);
5651                 }
5652                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
5653         } else {
5654                 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_1_0.update_fail_malformed_htlcs[0]);
5655         };
5656
5657         commitment_signed_dance!(nodes[0], nodes[1], update_1_0.commitment_signed, false, true);
5658
5659         let events = nodes[0].node.get_and_clear_pending_events();
5660         assert_eq!(events.len(), 1);
5661         if let &Event::PaymentFailed { payment_hash:_, ref rejected_by_dest, ref error_code, error_data: _ } = &events[0] {
5662                 assert_eq!(*rejected_by_dest, !expected_retryable);
5663                 assert_eq!(*error_code, expected_error_code);
5664         } else {
5665                 panic!("Uexpected event");
5666         }
5667
5668         let events = nodes[0].node.get_and_clear_pending_msg_events();
5669         if expected_channel_update.is_some() {
5670                 assert_eq!(events.len(), 1);
5671                 match events[0] {
5672                         MessageSendEvent::PaymentFailureNetworkUpdate { ref update } => {
5673                                 match update {
5674                                         &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {
5675                                                 if let HTLCFailChannelUpdate::ChannelUpdateMessage { .. } = expected_channel_update.unwrap() {} else {
5676                                                         panic!("channel_update not found!");
5677                                                 }
5678                                         },
5679                                         &HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, ref is_permanent } => {
5680                                                 if let HTLCFailChannelUpdate::ChannelClosed { short_channel_id: ref expected_short_channel_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
5681                                                         assert!(*short_channel_id == *expected_short_channel_id);
5682                                                         assert!(*is_permanent == *expected_is_permanent);
5683                                                 } else {
5684                                                         panic!("Unexpected message event");
5685                                                 }
5686                                         },
5687                                         &HTLCFailChannelUpdate::NodeFailure { ref node_id, ref is_permanent } => {
5688                                                 if let HTLCFailChannelUpdate::NodeFailure { node_id: ref expected_node_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
5689                                                         assert!(*node_id == *expected_node_id);
5690                                                         assert!(*is_permanent == *expected_is_permanent);
5691                                                 } else {
5692                                                         panic!("Unexpected message event");
5693                                                 }
5694                                         },
5695                                 }
5696                         },
5697                         _ => panic!("Unexpected message event"),
5698                 }
5699         } else {
5700                 assert_eq!(events.len(), 0);
5701         }
5702 }
5703
5704 impl msgs::ChannelUpdate {
5705         fn dummy() -> msgs::ChannelUpdate {
5706                 use bitcoin::secp256k1::ffi::Signature as FFISignature;
5707                 use bitcoin::secp256k1::Signature;
5708                 msgs::ChannelUpdate {
5709                         signature: Signature::from(FFISignature::new()),
5710                         contents: msgs::UnsignedChannelUpdate {
5711                                 chain_hash: BlockHash::hash(&vec![0u8][..]),
5712                                 short_channel_id: 0,
5713                                 timestamp: 0,
5714                                 flags: 0,
5715                                 cltv_expiry_delta: 0,
5716                                 htlc_minimum_msat: 0,
5717                                 fee_base_msat: 0,
5718                                 fee_proportional_millionths: 0,
5719                                 excess_data: vec![],
5720                         }
5721                 }
5722         }
5723 }
5724
5725 struct BogusOnionHopData {
5726         data: Vec<u8>
5727 }
5728 impl BogusOnionHopData {
5729         fn new(orig: msgs::OnionHopData) -> Self {
5730                 Self { data: orig.encode() }
5731         }
5732 }
5733 impl Writeable for BogusOnionHopData {
5734         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
5735                 writer.write_all(&self.data[..])
5736         }
5737 }
5738
5739 #[test]
5740 fn test_onion_failure() {
5741         use ln::msgs::ChannelUpdate;
5742         use ln::channelmanager::CLTV_FAR_FAR_AWAY;
5743         use bitcoin::secp256k1;
5744
5745         const BADONION: u16 = 0x8000;
5746         const PERM: u16 = 0x4000;
5747         const NODE: u16 = 0x2000;
5748         const UPDATE: u16 = 0x1000;
5749
5750         let chanmon_cfgs = create_chanmon_cfgs(3);
5751         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5752         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5753         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5754         for node in nodes.iter() {
5755                 *node.keys_manager.override_session_priv.lock().unwrap() = Some(SecretKey::from_slice(&[3; 32]).unwrap());
5756         }
5757         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())];
5758         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5759         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5760         let logger = test_utils::TestLogger::new();
5761         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).unwrap();
5762         // positve case
5763         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 40000, 40_000);
5764
5765         // intermediate node failure
5766         run_onion_failure_test("invalid_realm", 0, &nodes, &route, &payment_hash, |msg| {
5767                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5768                 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5769                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5770                 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 40000, &None, cur_height).unwrap();
5771                 let mut new_payloads = Vec::new();
5772                 for payload in onion_payloads.drain(..) {
5773                         new_payloads.push(BogusOnionHopData::new(payload));
5774                 }
5775                 // break the first (non-final) hop payload by swapping the realm (0) byte for a byte
5776                 // describing a length-1 TLV payload, which is obviously bogus.
5777                 new_payloads[0].data[0] = 1;
5778                 msg.onion_routing_packet = onion_utils::construct_onion_packet_bogus_hopdata(new_payloads, onion_keys, [0; 32], &payment_hash);
5779         }, ||{}, 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
5780
5781         // final node failure
5782         run_onion_failure_test("invalid_realm", 3, &nodes, &route, &payment_hash, |msg| {
5783                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5784                 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5785                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5786                 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 40000, &None, cur_height).unwrap();
5787                 let mut new_payloads = Vec::new();
5788                 for payload in onion_payloads.drain(..) {
5789                         new_payloads.push(BogusOnionHopData::new(payload));
5790                 }
5791                 // break the last-hop payload by swapping the realm (0) byte for a byte describing a
5792                 // length-1 TLV payload, which is obviously bogus.
5793                 new_payloads[1].data[0] = 1;
5794                 msg.onion_routing_packet = onion_utils::construct_onion_packet_bogus_hopdata(new_payloads, onion_keys, [0; 32], &payment_hash);
5795         }, ||{}, false, Some(PERM|22), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
5796
5797         // the following three with run_onion_failure_test_with_fail_intercept() test only the origin node
5798         // receiving simulated fail messages
5799         // intermediate node failure
5800         run_onion_failure_test_with_fail_intercept("temporary_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
5801                 // trigger error
5802                 msg.amount_msat -= 1;
5803         }, |msg| {
5804                 // and tamper returning error message
5805                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5806                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5807                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], NODE|2, &[0;0]);
5808         }, ||{}, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][0].pubkey, is_permanent: false}));
5809
5810         // final node failure
5811         run_onion_failure_test_with_fail_intercept("temporary_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
5812                 // and tamper returning error message
5813                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5814                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5815                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], NODE|2, &[0;0]);
5816         }, ||{
5817                 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
5818         }, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][1].pubkey, is_permanent: false}));
5819
5820         // intermediate node failure
5821         run_onion_failure_test_with_fail_intercept("permanent_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
5822                 msg.amount_msat -= 1;
5823         }, |msg| {
5824                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5825                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5826                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|2, &[0;0]);
5827         }, ||{}, true, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][0].pubkey, is_permanent: true}));
5828
5829         // final node failure
5830         run_onion_failure_test_with_fail_intercept("permanent_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
5831                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5832                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5833                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|2, &[0;0]);
5834         }, ||{
5835                 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
5836         }, false, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][1].pubkey, is_permanent: true}));
5837
5838         // intermediate node failure
5839         run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
5840                 msg.amount_msat -= 1;
5841         }, |msg| {
5842                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5843                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5844                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|3, &[0;0]);
5845         }, ||{
5846                 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
5847         }, true, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][0].pubkey, is_permanent: true}));
5848
5849         // final node failure
5850         run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
5851                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5852                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5853                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|3, &[0;0]);
5854         }, ||{
5855                 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
5856         }, false, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][1].pubkey, is_permanent: true}));
5857
5858         run_onion_failure_test("invalid_onion_version", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.version = 1; }, ||{}, true,
5859                 Some(BADONION|PERM|4), None);
5860
5861         run_onion_failure_test("invalid_onion_hmac", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.hmac = [3; 32]; }, ||{}, true,
5862                 Some(BADONION|PERM|5), None);
5863
5864         run_onion_failure_test("invalid_onion_key", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.public_key = Err(secp256k1::Error::InvalidPublicKey);}, ||{}, true,
5865                 Some(BADONION|PERM|6), None);
5866
5867         run_onion_failure_test_with_fail_intercept("temporary_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
5868                 msg.amount_msat -= 1;
5869         }, |msg| {
5870                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5871                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5872                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], UPDATE|7, &ChannelUpdate::dummy().encode_with_len()[..]);
5873         }, ||{}, true, Some(UPDATE|7), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5874
5875         run_onion_failure_test_with_fail_intercept("permanent_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
5876                 msg.amount_msat -= 1;
5877         }, |msg| {
5878                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5879                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5880                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|8, &[0;0]);
5881                 // short_channel_id from the processing node
5882         }, ||{}, true, Some(PERM|8), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
5883
5884         run_onion_failure_test_with_fail_intercept("required_channel_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
5885                 msg.amount_msat -= 1;
5886         }, |msg| {
5887                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5888                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5889                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|9, &[0;0]);
5890                 // short_channel_id from the processing node
5891         }, ||{}, true, Some(PERM|9), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
5892
5893         let mut bogus_route = route.clone();
5894         bogus_route.paths[0][1].short_channel_id -= 1;
5895         run_onion_failure_test("unknown_next_peer", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(PERM|10),
5896           Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: bogus_route.paths[0][1].short_channel_id, is_permanent:true}));
5897
5898         let amt_to_forward = nodes[1].node.channel_state.lock().unwrap().by_id.get(&channels[1].2).unwrap().get_their_htlc_minimum_msat() - 1;
5899         let mut bogus_route = route.clone();
5900         let route_len = bogus_route.paths[0].len();
5901         bogus_route.paths[0][route_len-1].fee_msat = amt_to_forward;
5902         run_onion_failure_test("amount_below_minimum", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(UPDATE|11), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5903
5904         //TODO: with new config API, we will be able to generate both valid and
5905         //invalid channel_update cases.
5906         run_onion_failure_test("fee_insufficient", 0, &nodes, &route, &payment_hash, |msg| {
5907                 msg.amount_msat -= 1;
5908         }, || {}, true, Some(UPDATE|12), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
5909
5910         run_onion_failure_test("incorrect_cltv_expiry", 0, &nodes, &route, &payment_hash, |msg| {
5911                 // need to violate: cltv_expiry - cltv_expiry_delta >= outgoing_cltv_value
5912                 msg.cltv_expiry -= 1;
5913         }, || {}, true, Some(UPDATE|13), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
5914
5915         run_onion_failure_test("expiry_too_soon", 0, &nodes, &route, &payment_hash, |msg| {
5916                 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
5917                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5918
5919                 nodes[1].block_notifier.block_connected_checked(&header, height, &[], &[]);
5920         }, ||{}, true, Some(UPDATE|14), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5921
5922         run_onion_failure_test("unknown_payment_hash", 2, &nodes, &route, &payment_hash, |_| {}, || {
5923                 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
5924         }, false, Some(PERM|15), None);
5925
5926         run_onion_failure_test("final_expiry_too_soon", 1, &nodes, &route, &payment_hash, |msg| {
5927                 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
5928                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5929
5930                 nodes[2].block_notifier.block_connected_checked(&header, height, &[], &[]);
5931         }, || {}, true, Some(17), None);
5932
5933         run_onion_failure_test("final_incorrect_cltv_expiry", 1, &nodes, &route, &payment_hash, |_| {}, || {
5934                 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().forward_htlcs.iter_mut() {
5935                         for f in pending_forwards.iter_mut() {
5936                                 match f {
5937                                         &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
5938                                                 forward_info.outgoing_cltv_value += 1,
5939                                         _ => {},
5940                                 }
5941                         }
5942                 }
5943         }, true, Some(18), None);
5944
5945         run_onion_failure_test("final_incorrect_htlc_amount", 1, &nodes, &route, &payment_hash, |_| {}, || {
5946                 // violate amt_to_forward > msg.amount_msat
5947                 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().forward_htlcs.iter_mut() {
5948                         for f in pending_forwards.iter_mut() {
5949                                 match f {
5950                                         &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
5951                                                 forward_info.amt_to_forward -= 1,
5952                                         _ => {},
5953                                 }
5954                         }
5955                 }
5956         }, true, Some(19), None);
5957
5958         run_onion_failure_test("channel_disabled", 0, &nodes, &route, &payment_hash, |_| {}, || {
5959                 // disconnect event to the channel between nodes[1] ~ nodes[2]
5960                 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
5961                 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5962         }, true, Some(UPDATE|20), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5963         reconnect_nodes(&nodes[1], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5964
5965         run_onion_failure_test("expiry_too_far", 0, &nodes, &route, &payment_hash, |msg| {
5966                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5967                 let mut route = route.clone();
5968                 let height = 1;
5969                 route.paths[0][1].cltv_expiry_delta += CLTV_FAR_FAR_AWAY + route.paths[0][0].cltv_expiry_delta + 1;
5970                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5971                 let (onion_payloads, _, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 40000, &None, height).unwrap();
5972                 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
5973                 msg.cltv_expiry = htlc_cltv;
5974                 msg.onion_routing_packet = onion_packet;
5975         }, ||{}, true, Some(21), None);
5976 }
5977
5978 #[test]
5979 #[should_panic]
5980 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5981         let chanmon_cfgs = create_chanmon_cfgs(2);
5982         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5983         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5984         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5985         //Force duplicate channel ids
5986         for node in nodes.iter() {
5987                 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5988         }
5989
5990         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5991         let channel_value_satoshis=10000;
5992         let push_msat=10001;
5993         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5994         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5995         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5996
5997         //Create a second channel with a channel_id collision
5998         assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5999 }
6000
6001 #[test]
6002 fn bolt2_open_channel_sending_node_checks_part2() {
6003         let chanmon_cfgs = create_chanmon_cfgs(2);
6004         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6005         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6006         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6007
6008         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
6009         let channel_value_satoshis=2^24;
6010         let push_msat=10001;
6011         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6012
6013         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
6014         let channel_value_satoshis=10000;
6015         // Test when push_msat is equal to 1000 * funding_satoshis.
6016         let push_msat=1000*channel_value_satoshis+1;
6017         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6018
6019         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
6020         let channel_value_satoshis=10000;
6021         let push_msat=10001;
6022         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
6023         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6024         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
6025
6026         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
6027         // 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
6028         assert!(node0_to_1_send_open_channel.channel_flags<=1);
6029
6030         // 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.
6031         assert!(BREAKDOWN_TIMEOUT>0);
6032         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
6033
6034         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
6035         let chain_hash=genesis_block(Network::Testnet).header.bitcoin_hash();
6036         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
6037
6038         // 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.
6039         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
6040         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
6041         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
6042         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
6043         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6044 }
6045
6046 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6047 // 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.
6048 //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.
6049
6050 #[test]
6051 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6052         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6053         let chanmon_cfgs = create_chanmon_cfgs(2);
6054         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6055         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6056         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6057         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6058
6059         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6060         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6061         let logger = test_utils::TestLogger::new();
6062         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).unwrap();
6063         route.paths[0][0].fee_msat = 100;
6064
6065         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
6066                 assert_eq!(err, "Cannot send less than their minimum HTLC value"));
6067         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6068         nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6069 }
6070
6071 #[test]
6072 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6073         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6074         let chanmon_cfgs = create_chanmon_cfgs(2);
6075         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6076         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6077         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6078         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6079         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6080
6081         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6082         let logger = test_utils::TestLogger::new();
6083         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).unwrap();
6084         route.paths[0][0].fee_msat = 0;
6085         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
6086                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6087
6088         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6089         nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6090 }
6091
6092 #[test]
6093 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6094         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6095         let chanmon_cfgs = create_chanmon_cfgs(2);
6096         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6097         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6098         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6099         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6100
6101         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6102         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6103         let logger = test_utils::TestLogger::new();
6104         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).unwrap();
6105         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6106         check_added_monitors!(nodes[0], 1);
6107         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6108         updates.update_add_htlcs[0].amount_msat = 0;
6109
6110         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6111         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6112         check_closed_broadcast!(nodes[1], true).unwrap();
6113         check_added_monitors!(nodes[1], 1);
6114 }
6115
6116 #[test]
6117 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6118         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6119         //It is enforced when constructing a route.
6120         let chanmon_cfgs = create_chanmon_cfgs(2);
6121         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6122         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6123         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6124         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 0, InitFeatures::known(), InitFeatures::known());
6125         let logger = test_utils::TestLogger::new();
6126
6127         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6128
6129         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6130         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).unwrap();
6131         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::RouteError { err },
6132                 assert_eq!(err, "Channel CLTV overflowed?!"));
6133 }
6134
6135 #[test]
6136 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6137         //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.
6138         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6139         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6140         let chanmon_cfgs = create_chanmon_cfgs(2);
6141         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6142         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6143         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6144         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6145         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().their_max_accepted_htlcs as u64;
6146
6147         let logger = test_utils::TestLogger::new();
6148         for i in 0..max_accepted_htlcs {
6149                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6150                 let payment_event = {
6151                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6152                         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).unwrap();
6153                         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6154                         check_added_monitors!(nodes[0], 1);
6155
6156                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6157                         assert_eq!(events.len(), 1);
6158                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6159                                 assert_eq!(htlcs[0].htlc_id, i);
6160                         } else {
6161                                 assert!(false);
6162                         }
6163                         SendEvent::from_event(events.remove(0))
6164                 };
6165                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6166                 check_added_monitors!(nodes[1], 0);
6167                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6168
6169                 expect_pending_htlcs_forwardable!(nodes[1]);
6170                 expect_payment_received!(nodes[1], our_payment_hash, 100000);
6171         }
6172         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6173         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6174         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).unwrap();
6175         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
6176                 assert_eq!(err, "Cannot push more than their max accepted HTLCs"));
6177
6178         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6179         nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6180 }
6181
6182 #[test]
6183 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6184         //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.
6185         let chanmon_cfgs = create_chanmon_cfgs(2);
6186         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6187         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6188         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6189         let channel_value = 100000;
6190         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6191         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).their_max_htlc_value_in_flight_msat;
6192
6193         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight, max_in_flight);
6194
6195         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6196         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6197         let logger = test_utils::TestLogger::new();
6198         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).unwrap();
6199         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
6200                 assert_eq!(err, "Cannot send value that would put us over the max HTLC value in flight our peer will accept"));
6201
6202         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6203         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);
6204
6205         send_payment(&nodes[0], &[&nodes[1]], max_in_flight, max_in_flight);
6206 }
6207
6208 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6209 #[test]
6210 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6211         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
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 chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6217         let htlc_minimum_msat: u64;
6218         {
6219                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6220                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6221                 htlc_minimum_msat = channel.get_our_htlc_minimum_msat();
6222         }
6223
6224         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6225         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6226         let logger = test_utils::TestLogger::new();
6227         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).unwrap();
6228         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6229         check_added_monitors!(nodes[0], 1);
6230         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6231         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6232         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6233         assert!(nodes[1].node.list_channels().is_empty());
6234         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6235         assert_eq!(err_msg.data, "Remote side tried to send less than our minimum HTLC value");
6236         check_added_monitors!(nodes[1], 1);
6237 }
6238
6239 #[test]
6240 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6241         //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
6242         let chanmon_cfgs = create_chanmon_cfgs(2);
6243         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6244         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6245         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6246         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6247
6248         let their_channel_reserve = get_channel_value_stat!(nodes[0], chan.2).channel_reserve_msat;
6249
6250         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6251         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6252         let logger = test_utils::TestLogger::new();
6253         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).unwrap();
6254         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6255         check_added_monitors!(nodes[0], 1);
6256         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6257
6258         updates.update_add_htlcs[0].amount_msat = 5000000-their_channel_reserve+1;
6259         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6260
6261         assert!(nodes[1].node.list_channels().is_empty());
6262         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6263         assert_eq!(err_msg.data, "Remote HTLC add would put them under their reserve value");
6264         check_added_monitors!(nodes[1], 1);
6265 }
6266
6267 #[test]
6268 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6269         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6270         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6271         let chanmon_cfgs = create_chanmon_cfgs(2);
6272         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6273         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6274         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6275         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6276         let logger = test_utils::TestLogger::new();
6277
6278         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6279
6280         let session_priv = SecretKey::from_slice(&{
6281                 let mut session_key = [0; 32];
6282                 let mut rng = thread_rng();
6283                 rng.fill_bytes(&mut session_key);
6284                 session_key
6285         }).expect("RNG is bad!");
6286
6287         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6288         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).unwrap();
6289
6290         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
6291         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6292         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &None, cur_height).unwrap();
6293         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6294
6295         let mut msg = msgs::UpdateAddHTLC {
6296                 channel_id: chan.2,
6297                 htlc_id: 0,
6298                 amount_msat: 1000,
6299                 payment_hash: our_payment_hash,
6300                 cltv_expiry: htlc_cltv,
6301                 onion_routing_packet: onion_packet.clone(),
6302         };
6303
6304         for i in 0..super::channel::OUR_MAX_HTLCS {
6305                 msg.htlc_id = i as u64;
6306                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6307         }
6308         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6309         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6310
6311         assert!(nodes[1].node.list_channels().is_empty());
6312         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6313         assert_eq!(err_msg.data, "Remote tried to push more than our max accepted HTLCs");
6314         check_added_monitors!(nodes[1], 1);
6315 }
6316
6317 #[test]
6318 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6319         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6320         let chanmon_cfgs = create_chanmon_cfgs(2);
6321         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6322         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6323         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6324         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6325         let logger = test_utils::TestLogger::new();
6326
6327         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6328         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6329         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).unwrap();
6330         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6331         check_added_monitors!(nodes[0], 1);
6332         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6333         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).their_max_htlc_value_in_flight_msat + 1;
6334         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6335
6336         assert!(nodes[1].node.list_channels().is_empty());
6337         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6338         assert_eq!(err_msg.data,"Remote HTLC add would put them over our max HTLC value");
6339         check_added_monitors!(nodes[1], 1);
6340 }
6341
6342 #[test]
6343 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6344         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6345         let chanmon_cfgs = create_chanmon_cfgs(2);
6346         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6347         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6348         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6349         let logger = test_utils::TestLogger::new();
6350
6351         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6352         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6353         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6354         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).unwrap();
6355         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6356         check_added_monitors!(nodes[0], 1);
6357         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6358         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6359         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6360
6361         assert!(nodes[1].node.list_channels().is_empty());
6362         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6363         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6364         check_added_monitors!(nodes[1], 1);
6365 }
6366
6367 #[test]
6368 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6369         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6370         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6371         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6372         let chanmon_cfgs = create_chanmon_cfgs(2);
6373         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6374         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6375         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6376         let logger = test_utils::TestLogger::new();
6377
6378         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6379         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6380         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6381         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).unwrap();
6382         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6383         check_added_monitors!(nodes[0], 1);
6384         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6385         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6386
6387         //Disconnect and Reconnect
6388         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6389         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6390         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6391         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6392         assert_eq!(reestablish_1.len(), 1);
6393         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6394         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6395         assert_eq!(reestablish_2.len(), 1);
6396         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6397         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6398         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6399         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6400
6401         //Resend HTLC
6402         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6403         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6404         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6405         check_added_monitors!(nodes[1], 1);
6406         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6407
6408         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6409
6410         assert!(nodes[1].node.list_channels().is_empty());
6411         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6412         assert_eq!(err_msg.data, "Remote skipped HTLC ID");
6413         check_added_monitors!(nodes[1], 1);
6414 }
6415
6416 #[test]
6417 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6418         //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.
6419
6420         let chanmon_cfgs = create_chanmon_cfgs(2);
6421         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6422         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6423         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6424         let logger = test_utils::TestLogger::new();
6425         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6426         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6427         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6428         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).unwrap();
6429         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6430
6431         check_added_monitors!(nodes[0], 1);
6432         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6433         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6434
6435         let update_msg = msgs::UpdateFulfillHTLC{
6436                 channel_id: chan.2,
6437                 htlc_id: 0,
6438                 payment_preimage: our_payment_preimage,
6439         };
6440
6441         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6442
6443         assert!(nodes[0].node.list_channels().is_empty());
6444         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6445         assert_eq!(err_msg.data, "Remote tried to fulfill/fail HTLC before it had been committed");
6446         check_added_monitors!(nodes[0], 1);
6447 }
6448
6449 #[test]
6450 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6451         //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.
6452
6453         let chanmon_cfgs = create_chanmon_cfgs(2);
6454         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6455         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6456         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6457         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6458         let logger = test_utils::TestLogger::new();
6459
6460         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6461         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6462         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).unwrap();
6463         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6464         check_added_monitors!(nodes[0], 1);
6465         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6466         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6467
6468         let update_msg = msgs::UpdateFailHTLC{
6469                 channel_id: chan.2,
6470                 htlc_id: 0,
6471                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6472         };
6473
6474         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6475
6476         assert!(nodes[0].node.list_channels().is_empty());
6477         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6478         assert_eq!(err_msg.data, "Remote tried to fulfill/fail HTLC before it had been committed");
6479         check_added_monitors!(nodes[0], 1);
6480 }
6481
6482 #[test]
6483 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6484         //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.
6485
6486         let chanmon_cfgs = create_chanmon_cfgs(2);
6487         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6488         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6489         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6490         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6491         let logger = test_utils::TestLogger::new();
6492
6493         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6494         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6495         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).unwrap();
6496         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6497         check_added_monitors!(nodes[0], 1);
6498         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6499         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6500
6501         let update_msg = msgs::UpdateFailMalformedHTLC{
6502                 channel_id: chan.2,
6503                 htlc_id: 0,
6504                 sha256_of_onion: [1; 32],
6505                 failure_code: 0x8000,
6506         };
6507
6508         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6509
6510         assert!(nodes[0].node.list_channels().is_empty());
6511         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6512         assert_eq!(err_msg.data, "Remote tried to fulfill/fail HTLC before it had been committed");
6513         check_added_monitors!(nodes[0], 1);
6514 }
6515
6516 #[test]
6517 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6518         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6519
6520         let chanmon_cfgs = create_chanmon_cfgs(2);
6521         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6522         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6523         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6524         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6525
6526         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6527
6528         nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6529         check_added_monitors!(nodes[1], 1);
6530
6531         let events = nodes[1].node.get_and_clear_pending_msg_events();
6532         assert_eq!(events.len(), 1);
6533         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6534                 match events[0] {
6535                         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, .. } } => {
6536                                 assert!(update_add_htlcs.is_empty());
6537                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6538                                 assert!(update_fail_htlcs.is_empty());
6539                                 assert!(update_fail_malformed_htlcs.is_empty());
6540                                 assert!(update_fee.is_none());
6541                                 update_fulfill_htlcs[0].clone()
6542                         },
6543                         _ => panic!("Unexpected event"),
6544                 }
6545         };
6546
6547         update_fulfill_msg.htlc_id = 1;
6548
6549         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6550
6551         assert!(nodes[0].node.list_channels().is_empty());
6552         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6553         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6554         check_added_monitors!(nodes[0], 1);
6555 }
6556
6557 #[test]
6558 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6559         //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.
6560
6561         let chanmon_cfgs = create_chanmon_cfgs(2);
6562         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6563         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6564         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6565         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6566
6567         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6568
6569         nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6570         check_added_monitors!(nodes[1], 1);
6571
6572         let events = nodes[1].node.get_and_clear_pending_msg_events();
6573         assert_eq!(events.len(), 1);
6574         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6575                 match events[0] {
6576                         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, .. } } => {
6577                                 assert!(update_add_htlcs.is_empty());
6578                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6579                                 assert!(update_fail_htlcs.is_empty());
6580                                 assert!(update_fail_malformed_htlcs.is_empty());
6581                                 assert!(update_fee.is_none());
6582                                 update_fulfill_htlcs[0].clone()
6583                         },
6584                         _ => panic!("Unexpected event"),
6585                 }
6586         };
6587
6588         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6589
6590         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6591
6592         assert!(nodes[0].node.list_channels().is_empty());
6593         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6594         assert_eq!(err_msg.data, "Remote tried to fulfill HTLC with an incorrect preimage");
6595         check_added_monitors!(nodes[0], 1);
6596 }
6597
6598 #[test]
6599 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6600         //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.
6601
6602         let chanmon_cfgs = create_chanmon_cfgs(2);
6603         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6604         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6605         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6606         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6607         let logger = test_utils::TestLogger::new();
6608
6609         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6610         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6611         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).unwrap();
6612         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6613         check_added_monitors!(nodes[0], 1);
6614
6615         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6616         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6617
6618         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6619         check_added_monitors!(nodes[1], 0);
6620         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6621
6622         let events = nodes[1].node.get_and_clear_pending_msg_events();
6623
6624         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6625                 match events[0] {
6626                         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, .. } } => {
6627                                 assert!(update_add_htlcs.is_empty());
6628                                 assert!(update_fulfill_htlcs.is_empty());
6629                                 assert!(update_fail_htlcs.is_empty());
6630                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6631                                 assert!(update_fee.is_none());
6632                                 update_fail_malformed_htlcs[0].clone()
6633                         },
6634                         _ => panic!("Unexpected event"),
6635                 }
6636         };
6637         update_msg.failure_code &= !0x8000;
6638         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6639
6640         assert!(nodes[0].node.list_channels().is_empty());
6641         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6642         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6643         check_added_monitors!(nodes[0], 1);
6644 }
6645
6646 #[test]
6647 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6648         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6649         //    * 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.
6650
6651         let chanmon_cfgs = create_chanmon_cfgs(3);
6652         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6653         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6654         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6655         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6656         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6657         let logger = test_utils::TestLogger::new();
6658
6659         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6660
6661         //First hop
6662         let mut payment_event = {
6663                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6664                 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).unwrap();
6665                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6666                 check_added_monitors!(nodes[0], 1);
6667                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6668                 assert_eq!(events.len(), 1);
6669                 SendEvent::from_event(events.remove(0))
6670         };
6671         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6672         check_added_monitors!(nodes[1], 0);
6673         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6674         expect_pending_htlcs_forwardable!(nodes[1]);
6675         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6676         assert_eq!(events_2.len(), 1);
6677         check_added_monitors!(nodes[1], 1);
6678         payment_event = SendEvent::from_event(events_2.remove(0));
6679         assert_eq!(payment_event.msgs.len(), 1);
6680
6681         //Second Hop
6682         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6683         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6684         check_added_monitors!(nodes[2], 0);
6685         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6686
6687         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6688         assert_eq!(events_3.len(), 1);
6689         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6690                 match events_3[0] {
6691                         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 } } => {
6692                                 assert!(update_add_htlcs.is_empty());
6693                                 assert!(update_fulfill_htlcs.is_empty());
6694                                 assert!(update_fail_htlcs.is_empty());
6695                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6696                                 assert!(update_fee.is_none());
6697                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6698                         },
6699                         _ => panic!("Unexpected event"),
6700                 }
6701         };
6702
6703         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6704
6705         check_added_monitors!(nodes[1], 0);
6706         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6707         expect_pending_htlcs_forwardable!(nodes[1]);
6708         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6709         assert_eq!(events_4.len(), 1);
6710
6711         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6712         match events_4[0] {
6713                 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, .. } } => {
6714                         assert!(update_add_htlcs.is_empty());
6715                         assert!(update_fulfill_htlcs.is_empty());
6716                         assert_eq!(update_fail_htlcs.len(), 1);
6717                         assert!(update_fail_malformed_htlcs.is_empty());
6718                         assert!(update_fee.is_none());
6719                 },
6720                 _ => panic!("Unexpected event"),
6721         };
6722
6723         check_added_monitors!(nodes[1], 1);
6724 }
6725
6726 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6727         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6728         // 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
6729         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6730
6731         let chanmon_cfgs = create_chanmon_cfgs(2);
6732         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6733         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6734         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6735         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6736
6737         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6738
6739         // We route 2 dust-HTLCs between A and B
6740         let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6741         let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6742         route_payment(&nodes[0], &[&nodes[1]], 1000000);
6743
6744         // Cache one local commitment tx as previous
6745         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6746
6747         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6748         assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2, &None));
6749         check_added_monitors!(nodes[1], 0);
6750         expect_pending_htlcs_forwardable!(nodes[1]);
6751         check_added_monitors!(nodes[1], 1);
6752
6753         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6754         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6755         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6756         check_added_monitors!(nodes[0], 1);
6757
6758         // Cache one local commitment tx as lastest
6759         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6760
6761         let events = nodes[0].node.get_and_clear_pending_msg_events();
6762         match events[0] {
6763                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6764                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6765                 },
6766                 _ => panic!("Unexpected event"),
6767         }
6768         match events[1] {
6769                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6770                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6771                 },
6772                 _ => panic!("Unexpected event"),
6773         }
6774
6775         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6776         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6777         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6778
6779         if announce_latest {
6780                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_last_commitment_tx[0].clone()]}, 1);
6781         } else {
6782                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_prev_commitment_tx[0].clone()]}, 1);
6783         }
6784
6785         check_closed_broadcast!(nodes[0], false);
6786         check_added_monitors!(nodes[0], 1);
6787
6788         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6789         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 1, true,  header.bitcoin_hash());
6790         let events = nodes[0].node.get_and_clear_pending_events();
6791         // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
6792         assert_eq!(events.len(), 2);
6793         let mut first_failed = false;
6794         for event in events {
6795                 match event {
6796                         Event::PaymentFailed { payment_hash, .. } => {
6797                                 if payment_hash == payment_hash_1 {
6798                                         assert!(!first_failed);
6799                                         first_failed = true;
6800                                 } else {
6801                                         assert_eq!(payment_hash, payment_hash_2);
6802                                 }
6803                         }
6804                         _ => panic!("Unexpected event"),
6805                 }
6806         }
6807 }
6808
6809 #[test]
6810 fn test_failure_delay_dust_htlc_local_commitment() {
6811         do_test_failure_delay_dust_htlc_local_commitment(true);
6812         do_test_failure_delay_dust_htlc_local_commitment(false);
6813 }
6814
6815 #[test]
6816 fn test_no_failure_dust_htlc_local_commitment() {
6817         // Transaction filters for failing back dust htlc based on local commitment txn infos has been
6818         // prone to error, we test here that a dummy transaction don't fail them.
6819
6820         let chanmon_cfgs = create_chanmon_cfgs(2);
6821         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6822         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6823         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6824         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6825
6826         // Rebalance a bit
6827         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
6828
6829         let as_dust_limit = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6830         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6831
6832         // We route 2 dust-HTLCs between A and B
6833         let (preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6834         let (preimage_2, _) = route_payment(&nodes[1], &[&nodes[0]], as_dust_limit*1000);
6835
6836         // Build a dummy invalid transaction trying to spend a commitment tx
6837         let input = TxIn {
6838                 previous_output: BitcoinOutPoint { txid: chan.3.txid(), vout: 0 },
6839                 script_sig: Script::new(),
6840                 sequence: 0,
6841                 witness: Vec::new(),
6842         };
6843
6844         let outp = TxOut {
6845                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
6846                 value: 10000,
6847         };
6848
6849         let dummy_tx = Transaction {
6850                 version: 2,
6851                 lock_time: 0,
6852                 input: vec![input],
6853                 output: vec![outp]
6854         };
6855
6856         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6857         nodes[0].chan_monitor.simple_monitor.block_connected(&header, 1, &[&dummy_tx], &[1;1]);
6858         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6859         assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
6860         // We broadcast a few more block to check everything is all right
6861         connect_blocks(&nodes[0].block_notifier, 20, 1, true,  header.bitcoin_hash());
6862         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6863         assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
6864
6865         claim_payment(&nodes[0], &vec!(&nodes[1])[..], preimage_1, bs_dust_limit*1000);
6866         claim_payment(&nodes[1], &vec!(&nodes[0])[..], preimage_2, as_dust_limit*1000);
6867 }
6868
6869 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6870         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6871         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6872         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6873         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6874         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6875         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6876
6877         let chanmon_cfgs = create_chanmon_cfgs(3);
6878         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6879         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6880         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6881         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6882
6883         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6884
6885         let (_payment_preimage_1, dust_hash) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6886         let (_payment_preimage_2, non_dust_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6887
6888         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6889         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6890
6891         // We revoked bs_commitment_tx
6892         if revoked {
6893                 let (payment_preimage_3, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6894                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 1_000_000);
6895         }
6896
6897         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6898         let mut timeout_tx = Vec::new();
6899         if local {
6900                 // We fail dust-HTLC 1 by broadcast of local commitment tx
6901                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_commitment_tx[0].clone()]}, 1);
6902                 check_closed_broadcast!(nodes[0], false);
6903                 check_added_monitors!(nodes[0], 1);
6904                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6905                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6906                 let parent_hash  = connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 2, true, header.bitcoin_hash());
6907                 expect_payment_failed!(nodes[0], dust_hash, true);
6908                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6909                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6910                 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6911                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6912                 nodes[0].block_notifier.block_connected(&Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
6913                 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6914                 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 8, true, header_3.bitcoin_hash());
6915                 expect_payment_failed!(nodes[0], non_dust_hash, true);
6916         } else {
6917                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6918                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![bs_commitment_tx[0].clone()]}, 1);
6919                 check_closed_broadcast!(nodes[0], false);
6920                 check_added_monitors!(nodes[0], 1);
6921                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6922                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6923                 let parent_hash  = connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 2, true, header.bitcoin_hash());
6924                 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6925                 if !revoked {
6926                         expect_payment_failed!(nodes[0], dust_hash, true);
6927                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6928                         // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
6929                         nodes[0].block_notifier.block_connected(&Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
6930                         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6931                         let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6932                         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 8, true, header_3.bitcoin_hash());
6933                         expect_payment_failed!(nodes[0], non_dust_hash, true);
6934                 } else {
6935                         // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
6936                         // commitment tx
6937                         let events = nodes[0].node.get_and_clear_pending_events();
6938                         assert_eq!(events.len(), 2);
6939                         let first;
6940                         match events[0] {
6941                                 Event::PaymentFailed { payment_hash, .. } => {
6942                                         if payment_hash == dust_hash { first = true; }
6943                                         else { first = false; }
6944                                 },
6945                                 _ => panic!("Unexpected event"),
6946                         }
6947                         match events[1] {
6948                                 Event::PaymentFailed { payment_hash, .. } => {
6949                                         if first { assert_eq!(payment_hash, non_dust_hash); }
6950                                         else { assert_eq!(payment_hash, dust_hash); }
6951                                 },
6952                                 _ => panic!("Unexpected event"),
6953                         }
6954                 }
6955         }
6956 }
6957
6958 #[test]
6959 fn test_sweep_outbound_htlc_failure_update() {
6960         do_test_sweep_outbound_htlc_failure_update(false, true);
6961         do_test_sweep_outbound_htlc_failure_update(false, false);
6962         do_test_sweep_outbound_htlc_failure_update(true, false);
6963 }
6964
6965 #[test]
6966 fn test_upfront_shutdown_script() {
6967         // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
6968         // enforce it at shutdown message
6969
6970         let mut config = UserConfig::default();
6971         config.channel_options.announced_channel = true;
6972         config.peer_channel_config_limits.force_announced_channel_preference = false;
6973         config.channel_options.commit_upfront_shutdown_pubkey = false;
6974         let user_cfgs = [None, Some(config), None];
6975         let chanmon_cfgs = create_chanmon_cfgs(3);
6976         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6977         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
6978         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6979
6980         // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
6981         let flags = InitFeatures::known();
6982         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
6983         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
6984         let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
6985         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6986         // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that  we disconnect peer
6987         nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
6988         assert_eq!(check_closed_broadcast!(nodes[2], true).unwrap().data, "Got shutdown request with a scriptpubkey which did not match their previous scriptpubkey");
6989         check_added_monitors!(nodes[2], 1);
6990
6991         // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
6992         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
6993         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
6994         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
6995         // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
6996         nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
6997         let events = nodes[2].node.get_and_clear_pending_msg_events();
6998         assert_eq!(events.len(), 1);
6999         match events[0] {
7000                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7001                 _ => panic!("Unexpected event"),
7002         }
7003
7004         // We test that if case of peer non-signaling we don't enforce committed script at channel opening
7005         let flags_no = InitFeatures::known().clear_upfront_shutdown_script();
7006         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone());
7007         nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7008         let mut node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
7009         node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7010         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_1_shutdown);
7011         let events = nodes[1].node.get_and_clear_pending_msg_events();
7012         assert_eq!(events.len(), 1);
7013         match events[0] {
7014                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7015                 _ => panic!("Unexpected event"),
7016         }
7017
7018         // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7019         // channel smoothly, opt-out is from channel initiator here
7020         let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone());
7021         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7022         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7023         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7024         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
7025         let events = nodes[0].node.get_and_clear_pending_msg_events();
7026         assert_eq!(events.len(), 1);
7027         match events[0] {
7028                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7029                 _ => panic!("Unexpected event"),
7030         }
7031
7032         //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7033         //// channel smoothly
7034         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone());
7035         nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7036         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7037         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7038         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
7039         let events = nodes[0].node.get_and_clear_pending_msg_events();
7040         assert_eq!(events.len(), 2);
7041         match events[0] {
7042                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7043                 _ => panic!("Unexpected event"),
7044         }
7045         match events[1] {
7046                 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7047                 _ => panic!("Unexpected event"),
7048         }
7049 }
7050
7051 #[test]
7052 fn test_user_configurable_csv_delay() {
7053         // We test our channel constructors yield errors when we pass them absurd csv delay
7054
7055         let mut low_our_to_self_config = UserConfig::default();
7056         low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7057         let mut high_their_to_self_config = UserConfig::default();
7058         high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7059         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7060         let chanmon_cfgs = create_chanmon_cfgs(2);
7061         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7062         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7063         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7064
7065         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7066         let keys_manager: Arc<KeysInterface<ChanKeySigner = EnforcingChannelKeys>> = Arc::new(test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet));
7067         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, &low_our_to_self_config) {
7068                 match error {
7069                         APIError::APIMisuseError { err } => { assert_eq!(err, "Configured with an unreasonable our_to_self_delay putting user funds at risks"); },
7070                         _ => panic!("Unexpected event"),
7071                 }
7072         } else { assert!(false) }
7073
7074         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7075         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7076         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7077         open_channel.to_self_delay = 200;
7078         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, &low_our_to_self_config) {
7079                 match error {
7080                         ChannelError::Close(err) => { assert_eq!(err, "Configured with an unreasonable our_to_self_delay putting user funds at risks"); },
7081                         _ => panic!("Unexpected event"),
7082                 }
7083         } else { assert!(false); }
7084
7085         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7086         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7087         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()));
7088         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7089         accept_channel.to_self_delay = 200;
7090         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7091         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7092                 match action {
7093                         &ErrorAction::SendErrorMessage { ref msg } => {
7094                                 assert_eq!(msg.data,"They wanted our payments to be delayed by a needlessly long period");
7095                         },
7096                         _ => { assert!(false); }
7097                 }
7098         } else { assert!(false); }
7099
7100         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7101         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7102         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7103         open_channel.to_self_delay = 200;
7104         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, &high_their_to_self_config) {
7105                 match error {
7106                         ChannelError::Close(err) => { assert_eq!(err, "They wanted our payments to be delayed by a needlessly long period"); },
7107                         _ => panic!("Unexpected event"),
7108                 }
7109         } else { assert!(false); }
7110 }
7111
7112 #[test]
7113 fn test_data_loss_protect() {
7114         // We want to be sure that :
7115         // * we don't broadcast our Local Commitment Tx in case of fallen behind
7116         // * we close channel in case of detecting other being fallen behind
7117         // * we are able to claim our own outputs thanks to to_remote being static
7118         let keys_manager;
7119         let logger;
7120         let fee_estimator;
7121         let tx_broadcaster;
7122         let chain_monitor;
7123         let monitor;
7124         let node_state_0;
7125         let chanmon_cfgs = create_chanmon_cfgs(2);
7126         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7127         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7128         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7129
7130         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7131
7132         // Cache node A state before any channel update
7133         let previous_node_state = nodes[0].node.encode();
7134         let mut previous_chan_monitor_state = test_utils::TestVecWriter(Vec::new());
7135         nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut previous_chan_monitor_state).unwrap();
7136
7137         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7138         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7139
7140         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7141         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7142
7143         // Restore node A from previous state
7144         logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7145         let mut chan_monitor = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut ::std::io::Cursor::new(previous_chan_monitor_state.0)).unwrap().1;
7146         chain_monitor = ChainWatchInterfaceUtil::new(Network::Testnet);
7147         tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
7148         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
7149         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
7150         monitor = test_utils::TestChannelMonitor::new(&chain_monitor, &tx_broadcaster, &logger, &fee_estimator);
7151         node_state_0 = {
7152                 let mut channel_monitors = HashMap::new();
7153                 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chan_monitor);
7154                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut ::std::io::Cursor::new(previous_node_state), ChannelManagerReadArgs {
7155                         keys_manager: &keys_manager,
7156                         fee_estimator: &fee_estimator,
7157                         monitor: &monitor,
7158                         logger: &logger,
7159                         tx_broadcaster: &tx_broadcaster,
7160                         default_config: UserConfig::default(),
7161                         channel_monitors: &mut channel_monitors,
7162                 }).unwrap().1
7163         };
7164         nodes[0].node = &node_state_0;
7165         assert!(monitor.add_monitor(OutPoint { txid: chan.3.txid(), index: 0 }, chan_monitor).is_ok());
7166         nodes[0].chan_monitor = &monitor;
7167         nodes[0].chain_monitor = &chain_monitor;
7168
7169         nodes[0].block_notifier = BlockNotifier::new(&nodes[0].chain_monitor);
7170         nodes[0].block_notifier.register_listener(&nodes[0].chan_monitor.simple_monitor);
7171         nodes[0].block_notifier.register_listener(nodes[0].node);
7172
7173         check_added_monitors!(nodes[0], 1);
7174
7175         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7176         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7177
7178         let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7179
7180         // Check we don't broadcast any transactions following learning of per_commitment_point from B
7181         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7182         check_added_monitors!(nodes[0], 1);
7183
7184         {
7185                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7186                 assert_eq!(node_txn.len(), 0);
7187         }
7188
7189         let mut reestablish_1 = Vec::with_capacity(1);
7190         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7191                 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7192                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7193                         reestablish_1.push(msg.clone());
7194                 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7195                 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7196                         match action {
7197                                 &ErrorAction::SendErrorMessage { ref msg } => {
7198                                         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");
7199                                 },
7200                                 _ => panic!("Unexpected event!"),
7201                         }
7202                 } else {
7203                         panic!("Unexpected event")
7204                 }
7205         }
7206
7207         // Check we close channel detecting A is fallen-behind
7208         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7209         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7210         check_added_monitors!(nodes[1], 1);
7211
7212
7213         // Check A is able to claim to_remote output
7214         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7215         assert_eq!(node_txn.len(), 1);
7216         check_spends!(node_txn[0], chan.3);
7217         assert_eq!(node_txn[0].output.len(), 2);
7218         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
7219         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()]}, 0);
7220         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 0, true, header.bitcoin_hash());
7221         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
7222         assert_eq!(spend_txn.len(), 1);
7223         check_spends!(spend_txn[0], node_txn[0]);
7224 }
7225
7226 #[test]
7227 fn test_check_htlc_underpaying() {
7228         // Send payment through A -> B but A is maliciously
7229         // sending a probe payment (i.e less than expected value0
7230         // to B, B should refuse payment.
7231
7232         let chanmon_cfgs = create_chanmon_cfgs(2);
7233         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7234         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7235         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7236
7237         // Create some initial channels
7238         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7239
7240         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 10_000);
7241
7242         // Node 3 is expecting payment of 100_000 but receive 10_000,
7243         // fail htlc like we didn't know the preimage.
7244         nodes[1].node.claim_funds(payment_preimage, &None, 100_000);
7245         nodes[1].node.process_pending_htlc_forwards();
7246
7247         let events = nodes[1].node.get_and_clear_pending_msg_events();
7248         assert_eq!(events.len(), 1);
7249         let (update_fail_htlc, commitment_signed) = match events[0] {
7250                 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 } } => {
7251                         assert!(update_add_htlcs.is_empty());
7252                         assert!(update_fulfill_htlcs.is_empty());
7253                         assert_eq!(update_fail_htlcs.len(), 1);
7254                         assert!(update_fail_malformed_htlcs.is_empty());
7255                         assert!(update_fee.is_none());
7256                         (update_fail_htlcs[0].clone(), commitment_signed)
7257                 },
7258                 _ => panic!("Unexpected event"),
7259         };
7260         check_added_monitors!(nodes[1], 1);
7261
7262         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7263         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7264
7265         // 10_000 msat as u64, followed by a height of 99 as u32
7266         let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7267         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(99));
7268         expect_payment_failed!(nodes[0], payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7269         nodes[1].node.get_and_clear_pending_events();
7270 }
7271
7272 #[test]
7273 fn test_announce_disable_channels() {
7274         // Create 2 channels between A and B. Disconnect B. Call timer_chan_freshness_every_min and check for generated
7275         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7276
7277         let chanmon_cfgs = create_chanmon_cfgs(2);
7278         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7279         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7280         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7281
7282         let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7283         let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7284         let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7285
7286         // Disconnect peers
7287         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7288         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7289
7290         nodes[0].node.timer_chan_freshness_every_min(); // dirty -> stagged
7291         nodes[0].node.timer_chan_freshness_every_min(); // staged -> fresh
7292         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7293         assert_eq!(msg_events.len(), 3);
7294         for e in msg_events {
7295                 match e {
7296                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7297                                 let short_id = msg.contents.short_channel_id;
7298                                 // Check generated channel_update match list in PendingChannelUpdate
7299                                 if short_id != short_id_1 && short_id != short_id_2 && short_id != short_id_3 {
7300                                         panic!("Generated ChannelUpdate for wrong chan!");
7301                                 }
7302                         },
7303                         _ => panic!("Unexpected event"),
7304                 }
7305         }
7306         // Reconnect peers
7307         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7308         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7309         assert_eq!(reestablish_1.len(), 3);
7310         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7311         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7312         assert_eq!(reestablish_2.len(), 3);
7313
7314         // Reestablish chan_1
7315         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7316         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7317         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7318         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7319         // Reestablish chan_2
7320         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7321         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7322         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7323         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7324         // Reestablish chan_3
7325         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7326         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7327         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7328         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7329
7330         nodes[0].node.timer_chan_freshness_every_min();
7331         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7332 }
7333
7334 #[test]
7335 fn test_bump_penalty_txn_on_revoked_commitment() {
7336         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7337         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7338
7339         let chanmon_cfgs = create_chanmon_cfgs(2);
7340         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7341         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7342         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7343
7344         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7345         let logger = test_utils::TestLogger::new();
7346
7347
7348         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7349         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
7350         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).unwrap();
7351         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7352
7353         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7354         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7355         assert_eq!(revoked_txn[0].output.len(), 4);
7356         assert_eq!(revoked_txn[0].input.len(), 1);
7357         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7358         let revoked_txid = revoked_txn[0].txid();
7359
7360         let mut penalty_sum = 0;
7361         for outp in revoked_txn[0].output.iter() {
7362                 if outp.script_pubkey.is_v0_p2wsh() {
7363                         penalty_sum += outp.value;
7364                 }
7365         }
7366
7367         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7368         let header_114 = connect_blocks(&nodes[1].block_notifier, 114, 0, false, Default::default());
7369
7370         // Actually revoke tx by claiming a HTLC
7371         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7372         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7373         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_txn[0].clone()] }, 115);
7374         check_added_monitors!(nodes[1], 1);
7375
7376         // One or more justice tx should have been broadcast, check it
7377         let penalty_1;
7378         let feerate_1;
7379         {
7380                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7381                 assert_eq!(node_txn.len(), 3); // justice tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout (broadcasted from ChannelManager)
7382                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7383                 assert_eq!(node_txn[0].output.len(), 1);
7384                 check_spends!(node_txn[0], revoked_txn[0]);
7385                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7386                 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7387                 penalty_1 = node_txn[0].txid();
7388                 node_txn.clear();
7389         };
7390
7391         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7392         let header = connect_blocks(&nodes[1].block_notifier, 3, 115,  true, header.bitcoin_hash());
7393         let mut penalty_2 = penalty_1;
7394         let mut feerate_2 = 0;
7395         {
7396                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7397                 assert_eq!(node_txn.len(), 1);
7398                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7399                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7400                         assert_eq!(node_txn[0].output.len(), 1);
7401                         check_spends!(node_txn[0], revoked_txn[0]);
7402                         penalty_2 = node_txn[0].txid();
7403                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7404                         assert_ne!(penalty_2, penalty_1);
7405                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7406                         feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7407                         // Verify 25% bump heuristic
7408                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7409                         node_txn.clear();
7410                 }
7411         }
7412         assert_ne!(feerate_2, 0);
7413
7414         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7415         connect_blocks(&nodes[1].block_notifier, 3, 118, true, header);
7416         let penalty_3;
7417         let mut feerate_3 = 0;
7418         {
7419                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7420                 assert_eq!(node_txn.len(), 1);
7421                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7422                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7423                         assert_eq!(node_txn[0].output.len(), 1);
7424                         check_spends!(node_txn[0], revoked_txn[0]);
7425                         penalty_3 = node_txn[0].txid();
7426                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7427                         assert_ne!(penalty_3, penalty_2);
7428                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7429                         feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7430                         // Verify 25% bump heuristic
7431                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7432                         node_txn.clear();
7433                 }
7434         }
7435         assert_ne!(feerate_3, 0);
7436
7437         nodes[1].node.get_and_clear_pending_events();
7438         nodes[1].node.get_and_clear_pending_msg_events();
7439 }
7440
7441 #[test]
7442 fn test_bump_penalty_txn_on_revoked_htlcs() {
7443         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7444         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7445
7446         let chanmon_cfgs = create_chanmon_cfgs(2);
7447         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7448         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7449         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7450
7451         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7452         // Lock HTLC in both directions
7453         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3_000_000).0;
7454         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7455
7456         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7457         assert_eq!(revoked_local_txn[0].input.len(), 1);
7458         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7459
7460         // Revoke local commitment tx
7461         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7462
7463         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7464         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7465         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
7466         check_closed_broadcast!(nodes[1], false);
7467         check_added_monitors!(nodes[1], 1);
7468
7469         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7470         assert_eq!(revoked_htlc_txn.len(), 4);
7471         if revoked_htlc_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7472                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7473                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7474                 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7475                 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7476                 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7477         } else if revoked_htlc_txn[1].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7478                 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7479                 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7480                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7481                 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7482                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7483         }
7484
7485         // Broadcast set of revoked txn on A
7486         let header_128 = connect_blocks(&nodes[0].block_notifier, 128, 0, true, header.bitcoin_hash());
7487         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7488
7489         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7490         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);
7491         let first;
7492         let feerate_1;
7493         let penalty_txn;
7494         {
7495                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7496                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7497                 // Verify claim tx are spending revoked HTLC txn
7498                 assert_eq!(node_txn[4].input.len(), 2);
7499                 assert_eq!(node_txn[4].output.len(), 1);
7500                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7501                 first = node_txn[4].txid();
7502                 // Store both feerates for later comparison
7503                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[4].output[0].value;
7504                 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7505                 penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7506                 node_txn.clear();
7507         }
7508
7509         // Connect three more block to see if bumped penalty are issued for HTLC txn
7510         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7511         nodes[0].block_notifier.block_connected(&Block { header: header_130, txdata: penalty_txn }, 130);
7512         {
7513                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7514                 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7515
7516                 check_spends!(node_txn[0], revoked_local_txn[0]);
7517                 check_spends!(node_txn[1], revoked_local_txn[0]);
7518
7519                 node_txn.clear();
7520         };
7521
7522         // Few more blocks to confirm penalty txn
7523         let header_135 = connect_blocks(&nodes[0].block_notifier, 5, 130, true, header_130.bitcoin_hash());
7524         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7525         let header_144 = connect_blocks(&nodes[0].block_notifier, 9, 135, true, header_135);
7526         let node_txn = {
7527                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7528                 assert_eq!(node_txn.len(), 1);
7529
7530                 assert_eq!(node_txn[0].input.len(), 2);
7531                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7532                 // Verify bumped tx is different and 25% bump heuristic
7533                 assert_ne!(first, node_txn[0].txid());
7534                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7535                 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7536                 assert!(feerate_2 * 100 > feerate_1 * 125);
7537                 let txn = vec![node_txn[0].clone()];
7538                 node_txn.clear();
7539                 txn
7540         };
7541         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7542         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7543         nodes[0].block_notifier.block_connected(&Block { header: header_145, txdata: node_txn }, 145);
7544         connect_blocks(&nodes[0].block_notifier, 20, 145, true, header_145.bitcoin_hash());
7545         {
7546                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7547                 // We verify than no new transaction has been broadcast because previously
7548                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7549                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7550                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7551                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7552                 // up bumped justice generation.
7553                 assert_eq!(node_txn.len(), 0);
7554                 node_txn.clear();
7555         }
7556         check_closed_broadcast!(nodes[0], false);
7557         check_added_monitors!(nodes[0], 1);
7558 }
7559
7560 #[test]
7561 fn test_bump_penalty_txn_on_remote_commitment() {
7562         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7563         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7564
7565         // Create 2 HTLCs
7566         // Provide preimage for one
7567         // Check aggregation
7568
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
7574         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7575         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7576         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7577
7578         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7579         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7580         assert_eq!(remote_txn[0].output.len(), 4);
7581         assert_eq!(remote_txn[0].input.len(), 1);
7582         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7583
7584         // Claim a HTLC without revocation (provide B monitor with preimage)
7585         nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000);
7586         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7587         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
7588         check_added_monitors!(nodes[1], 2);
7589
7590         // One or more claim tx should have been broadcast, check it
7591         let timeout;
7592         let preimage;
7593         let feerate_timeout;
7594         let feerate_preimage;
7595         {
7596                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7597                 assert_eq!(node_txn.len(), 5); // 2 * claim tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout + local HTLC-success (broadcasted from ChannelManager)
7598                 assert_eq!(node_txn[0].input.len(), 1);
7599                 assert_eq!(node_txn[1].input.len(), 1);
7600                 check_spends!(node_txn[0], remote_txn[0]);
7601                 check_spends!(node_txn[1], remote_txn[0]);
7602                 check_spends!(node_txn[2], chan.3);
7603                 check_spends!(node_txn[3], node_txn[2]);
7604                 check_spends!(node_txn[4], node_txn[2]);
7605                 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7606                         timeout = node_txn[0].txid();
7607                         let index = node_txn[0].input[0].previous_output.vout;
7608                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7609                         feerate_timeout = fee * 1000 / node_txn[0].get_weight() as u64;
7610
7611                         preimage = node_txn[1].txid();
7612                         let index = node_txn[1].input[0].previous_output.vout;
7613                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7614                         feerate_preimage = fee * 1000 / node_txn[1].get_weight() as u64;
7615                 } else {
7616                         timeout = node_txn[1].txid();
7617                         let index = node_txn[1].input[0].previous_output.vout;
7618                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7619                         feerate_timeout = fee * 1000 / node_txn[1].get_weight() as u64;
7620
7621                         preimage = node_txn[0].txid();
7622                         let index = node_txn[0].input[0].previous_output.vout;
7623                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7624                         feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7625                 }
7626                 node_txn.clear();
7627         };
7628         assert_ne!(feerate_timeout, 0);
7629         assert_ne!(feerate_preimage, 0);
7630
7631         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7632         connect_blocks(&nodes[1].block_notifier, 15, 1,  true, header.bitcoin_hash());
7633         {
7634                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7635                 assert_eq!(node_txn.len(), 2);
7636                 assert_eq!(node_txn[0].input.len(), 1);
7637                 assert_eq!(node_txn[1].input.len(), 1);
7638                 check_spends!(node_txn[0], remote_txn[0]);
7639                 check_spends!(node_txn[1], remote_txn[0]);
7640                 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7641                         let index = node_txn[0].input[0].previous_output.vout;
7642                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7643                         let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7644                         assert!(new_feerate * 100 > feerate_timeout * 125);
7645                         assert_ne!(timeout, node_txn[0].txid());
7646
7647                         let index = node_txn[1].input[0].previous_output.vout;
7648                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7649                         let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7650                         assert!(new_feerate * 100 > feerate_preimage * 125);
7651                         assert_ne!(preimage, node_txn[1].txid());
7652                 } else {
7653                         let index = node_txn[1].input[0].previous_output.vout;
7654                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7655                         let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7656                         assert!(new_feerate * 100 > feerate_timeout * 125);
7657                         assert_ne!(timeout, node_txn[1].txid());
7658
7659                         let index = node_txn[0].input[0].previous_output.vout;
7660                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7661                         let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7662                         assert!(new_feerate * 100 > feerate_preimage * 125);
7663                         assert_ne!(preimage, node_txn[0].txid());
7664                 }
7665                 node_txn.clear();
7666         }
7667
7668         nodes[1].node.get_and_clear_pending_events();
7669         nodes[1].node.get_and_clear_pending_msg_events();
7670 }
7671
7672 #[test]
7673 fn test_set_outpoints_partial_claiming() {
7674         // - remote party claim tx, new bump tx
7675         // - disconnect remote claiming tx, new bump
7676         // - disconnect tx, see no tx anymore
7677         let chanmon_cfgs = create_chanmon_cfgs(2);
7678         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7679         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7680         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7681
7682         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7683         let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7684         let payment_preimage_2 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7685
7686         // Remote commitment txn with 4 outputs: to_local, to_remote, 2 outgoing HTLC
7687         let remote_txn = get_local_commitment_txn!(nodes[1], chan.2);
7688         assert_eq!(remote_txn.len(), 3);
7689         assert_eq!(remote_txn[0].output.len(), 4);
7690         assert_eq!(remote_txn[0].input.len(), 1);
7691         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7692         check_spends!(remote_txn[1], remote_txn[0]);
7693         check_spends!(remote_txn[2], remote_txn[0]);
7694
7695         // Connect blocks on node A to advance height towards TEST_FINAL_CLTV
7696         let prev_header_100 = connect_blocks(&nodes[1].block_notifier, 100, 0, false, Default::default());
7697         // Provide node A with both preimage
7698         nodes[0].node.claim_funds(payment_preimage_1, &None, 3_000_000);
7699         nodes[0].node.claim_funds(payment_preimage_2, &None, 3_000_000);
7700         check_added_monitors!(nodes[0], 2);
7701         nodes[0].node.get_and_clear_pending_events();
7702         nodes[0].node.get_and_clear_pending_msg_events();
7703
7704         // Connect blocks on node A commitment transaction
7705         let header = BlockHeader { version: 0x20000000, prev_blockhash: prev_header_100, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7706         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 101);
7707         check_closed_broadcast!(nodes[0], false);
7708         check_added_monitors!(nodes[0], 1);
7709         // Verify node A broadcast tx claiming both HTLCs
7710         {
7711                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7712                 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-Success*2
7713                 assert_eq!(node_txn.len(), 4);
7714                 check_spends!(node_txn[0], remote_txn[0]);
7715                 check_spends!(node_txn[1], chan.3);
7716                 check_spends!(node_txn[2], node_txn[1]);
7717                 check_spends!(node_txn[3], node_txn[1]);
7718                 assert_eq!(node_txn[0].input.len(), 2);
7719                 node_txn.clear();
7720         }
7721
7722         // Connect blocks on node B
7723         connect_blocks(&nodes[1].block_notifier, 135, 0, false, Default::default());
7724         check_closed_broadcast!(nodes[1], false);
7725         check_added_monitors!(nodes[1], 1);
7726         // Verify node B broadcast 2 HTLC-timeout txn
7727         let partial_claim_tx = {
7728                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7729                 assert_eq!(node_txn.len(), 3);
7730                 check_spends!(node_txn[1], node_txn[0]);
7731                 check_spends!(node_txn[2], node_txn[0]);
7732                 assert_eq!(node_txn[1].input.len(), 1);
7733                 assert_eq!(node_txn[2].input.len(), 1);
7734                 node_txn[1].clone()
7735         };
7736
7737         // Broadcast partial claim on node A, should regenerate a claiming tx with HTLC dropped
7738         let header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7739         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![partial_claim_tx.clone()] }, 102);
7740         {
7741                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7742                 assert_eq!(node_txn.len(), 1);
7743                 check_spends!(node_txn[0], remote_txn[0]);
7744                 assert_eq!(node_txn[0].input.len(), 1); //dropped HTLC
7745                 node_txn.clear();
7746         }
7747         nodes[0].node.get_and_clear_pending_msg_events();
7748
7749         // Disconnect last block on node A, should regenerate a claiming tx with HTLC dropped
7750         nodes[0].block_notifier.block_disconnected(&header, 102);
7751         {
7752                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7753                 assert_eq!(node_txn.len(), 1);
7754                 check_spends!(node_txn[0], remote_txn[0]);
7755                 assert_eq!(node_txn[0].input.len(), 2); //resurrected HTLC
7756                 node_txn.clear();
7757         }
7758
7759         //// Disconnect one more block and then reconnect multiple no transaction should be generated
7760         nodes[0].block_notifier.block_disconnected(&header, 101);
7761         connect_blocks(&nodes[1].block_notifier, 15, 101, false, prev_header_100);
7762         {
7763                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7764                 assert_eq!(node_txn.len(), 0);
7765                 node_txn.clear();
7766         }
7767 }
7768
7769 #[test]
7770 fn test_counterparty_raa_skip_no_crash() {
7771         // Previously, if our counterparty sent two RAAs in a row without us having provided a
7772         // commitment transaction, we would have happily carried on and provided them the next
7773         // commitment transaction based on one RAA forward. This would probably eventually have led to
7774         // channel closure, but it would not have resulted in funds loss. Still, our
7775         // EnforcingChannelKeys would have paniced as it doesn't like jumps into the future. Here, we
7776         // check simply that the channel is closed in response to such an RAA, but don't check whether
7777         // we decide to punish our counterparty for revoking their funds (as we don't currently
7778         // implement that).
7779         let chanmon_cfgs = create_chanmon_cfgs(2);
7780         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7781         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7782         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7783         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
7784
7785         let commitment_seed = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&channel_id).unwrap().local_keys.commitment_seed().clone();
7786         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7787         let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7788                 &SecretKey::from_slice(&chan_utils::build_commitment_secret(&commitment_seed, INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7789         let per_commitment_secret = chan_utils::build_commitment_secret(&commitment_seed, INITIAL_COMMITMENT_NUMBER);
7790
7791         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7792                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
7793         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7794         check_added_monitors!(nodes[1], 1);
7795 }
7796
7797 #[test]
7798 fn test_bump_txn_sanitize_tracking_maps() {
7799         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7800         // verify we clean then right after expiration of ANTI_REORG_DELAY.
7801
7802         let chanmon_cfgs = create_chanmon_cfgs(2);
7803         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7804         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7805         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7806
7807         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7808         // Lock HTLC in both directions
7809         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
7810         route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
7811
7812         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7813         assert_eq!(revoked_local_txn[0].input.len(), 1);
7814         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7815
7816         // Revoke local commitment tx
7817         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 9_000_000);
7818
7819         // Broadcast set of revoked txn on A
7820         let header_128 = connect_blocks(&nodes[0].block_notifier, 128, 0,  false, Default::default());
7821         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7822
7823         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7824         nodes[0].block_notifier.block_connected(&Block { header: header_129, txdata: vec![revoked_local_txn[0].clone()] }, 129);
7825         check_closed_broadcast!(nodes[0], false);
7826         check_added_monitors!(nodes[0], 1);
7827         let penalty_txn = {
7828                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7829                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
7830                 check_spends!(node_txn[0], revoked_local_txn[0]);
7831                 check_spends!(node_txn[1], revoked_local_txn[0]);
7832                 check_spends!(node_txn[2], revoked_local_txn[0]);
7833                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7834                 node_txn.clear();
7835                 penalty_txn
7836         };
7837         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7838         nodes[0].block_notifier.block_connected(&Block { header: header_130, txdata: penalty_txn }, 130);
7839         connect_blocks(&nodes[0].block_notifier, 5, 130,  false, header_130.bitcoin_hash());
7840         {
7841                 let monitors = nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap();
7842                 if let Some(monitor) = monitors.get(&OutPoint { txid: chan.3.txid(), index: 0 }) {
7843                         assert!(monitor.onchain_tx_handler.pending_claim_requests.is_empty());
7844                         assert!(monitor.onchain_tx_handler.claimable_outpoints.is_empty());
7845                 }
7846         }
7847 }
7848
7849 #[test]
7850 fn test_override_channel_config() {
7851         let chanmon_cfgs = create_chanmon_cfgs(2);
7852         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7853         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7854         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7855
7856         // Node0 initiates a channel to node1 using the override config.
7857         let mut override_config = UserConfig::default();
7858         override_config.own_channel_config.our_to_self_delay = 200;
7859
7860         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7861
7862         // Assert the channel created by node0 is using the override config.
7863         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7864         assert_eq!(res.channel_flags, 0);
7865         assert_eq!(res.to_self_delay, 200);
7866 }
7867
7868 #[test]
7869 fn test_override_0msat_htlc_minimum() {
7870         let mut zero_config = UserConfig::default();
7871         zero_config.own_channel_config.our_htlc_minimum_msat = 0;
7872         let chanmon_cfgs = create_chanmon_cfgs(2);
7873         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7874         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7875         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7876
7877         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7878         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7879         assert_eq!(res.htlc_minimum_msat, 1);
7880
7881         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
7882         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7883         assert_eq!(res.htlc_minimum_msat, 1);
7884 }
7885
7886 #[test]
7887 fn test_simple_payment_secret() {
7888         // Simple test of sending a payment with a payment_secret present. This does not use any AMP
7889         // features, however.
7890         let chanmon_cfgs = create_chanmon_cfgs(3);
7891         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7892         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7893         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7894
7895         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7896         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
7897         let logger = test_utils::TestLogger::new();
7898
7899         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
7900         let payment_secret = PaymentSecret([0xdb; 32]);
7901         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
7902         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).unwrap();
7903         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2]]], 100000, payment_hash, Some(payment_secret.clone()));
7904         // Claiming with all the correct values but the wrong secret should result in nothing...
7905         assert_eq!(nodes[2].node.claim_funds(payment_preimage, &None, 100_000), false);
7906         assert_eq!(nodes[2].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 100_000), false);
7907         // ...but with the right secret we should be able to claim all the way back
7908         claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage, Some(payment_secret.clone()), 100_000);
7909 }
7910
7911 #[test]
7912 fn test_simple_mpp() {
7913         // Simple test of sending a multi-path payment.
7914         let chanmon_cfgs = create_chanmon_cfgs(4);
7915         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7916         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
7917         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7918
7919         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7920         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7921         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7922         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7923         let logger = test_utils::TestLogger::new();
7924
7925         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
7926         let payment_secret = PaymentSecret([0xdb; 32]);
7927         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
7928         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).unwrap();
7929         let path = route.paths[0].clone();
7930         route.paths.push(path);
7931         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
7932         route.paths[0][0].short_channel_id = chan_1_id;
7933         route.paths[0][1].short_channel_id = chan_3_id;
7934         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
7935         route.paths[1][0].short_channel_id = chan_2_id;
7936         route.paths[1][1].short_channel_id = chan_4_id;
7937         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, Some(payment_secret.clone()));
7938         // Claiming with all the correct values but the wrong secret should result in nothing...
7939         assert_eq!(nodes[3].node.claim_funds(payment_preimage, &None, 200_000), false);
7940         assert_eq!(nodes[3].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 200_000), false);
7941         // ...but with the right secret we should be able to claim all the way back
7942         claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage, Some(payment_secret), 200_000);
7943 }
7944
7945 #[test]
7946 fn test_update_err_monitor_lockdown() {
7947         // Our monitor will lock update of local commitment transaction if a broadcastion condition
7948         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
7949         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
7950         //
7951         // This scenario may happen in a watchtower setup, where watchtower process a block height
7952         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
7953         // commitment at same time.
7954
7955         let chanmon_cfgs = create_chanmon_cfgs(2);
7956         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7957         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7958         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7959
7960         // Create some initial channel
7961         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7962         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
7963
7964         // Rebalance the network to generate htlc in the two directions
7965         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
7966
7967         // Route a HTLC from node 0 to node 1 (but don't settle)
7968         let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
7969
7970         // Copy SimpleManyChannelMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
7971         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7972         let chain_monitor = chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet);
7973         let watchtower = {
7974                 let monitors = nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap();
7975                 let monitor = monitors.get(&outpoint).unwrap();
7976                 let mut w = test_utils::TestVecWriter(Vec::new());
7977                 monitor.write_for_disk(&mut w).unwrap();
7978                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
7979                                 &mut ::std::io::Cursor::new(&w.0)).unwrap().1;
7980                 assert!(new_monitor == *monitor);
7981                 let watchtower = test_utils::TestChannelMonitor::new(&chain_monitor, &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator);
7982                 assert!(watchtower.add_monitor(outpoint, new_monitor).is_ok());
7983                 watchtower
7984         };
7985         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7986         watchtower.simple_monitor.block_connected(&header, 200, &vec![], &vec![]);
7987
7988         // Try to update ChannelMonitor
7989         assert!(nodes[1].node.claim_funds(preimage, &None, 9_000_000));
7990         check_added_monitors!(nodes[1], 1);
7991         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7992         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
7993         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
7994         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
7995                 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
7996                         if let Err(_) =  watchtower.simple_monitor.update_monitor(outpoint, update.clone()) {} else { assert!(false); }
7997                         if let Ok(_) = nodes[0].chan_monitor.update_monitor(outpoint, update) {} else { assert!(false); }
7998                 } else { assert!(false); }
7999         } else { assert!(false); };
8000         // Our local monitor is in-sync and hasn't processed yet timeout
8001         check_added_monitors!(nodes[0], 1);
8002         let events = nodes[0].node.get_and_clear_pending_events();
8003         assert_eq!(events.len(), 1);
8004 }