]> git.bitcoin.ninja Git - rust-lightning/blob - lightning/src/ln/functional_tests.rs
e00e036db53478279dcc8abf4e79af660f519d62
[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::{ChainListener, ChainWatchInterfaceUtil, BlockNotifier};
8 use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
9 use ln::channelmanager::{ChannelManager,ChannelManagerReadArgs,HTLCForwardInfo,RAACommitmentOrder, PaymentPreimage, PaymentHash, BREAKDOWN_TIMEOUT};
10 use ln::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ManyChannelMonitor, ANTI_REORG_DELAY};
11 use ln::channel::{Channel, ChannelError};
12 use ln::{chan_utils, onion_utils};
13 use ln::router::{Route, RouteHop};
14 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
15 use ln::msgs;
16 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler,HTLCFailChannelUpdate, ErrorAction};
17 use util::enforcing_trait_impls::EnforcingChannelKeys;
18 use util::test_utils;
19 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
20 use util::errors::APIError;
21 use util::ser::{Writeable, Writer, ReadableArgs};
22 use util::config::UserConfig;
23 use util::logger::Logger;
24
25 use bitcoin::util::hash::BitcoinHash;
26 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
27 use bitcoin::util::bip143;
28 use bitcoin::util::address::Address;
29 use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
30 use bitcoin::blockdata::block::{Block, BlockHeader};
31 use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType, OutPoint as BitcoinOutPoint};
32 use bitcoin::blockdata::script::{Builder, Script};
33 use bitcoin::blockdata::opcodes;
34 use bitcoin::blockdata::constants::genesis_block;
35 use bitcoin::network::constants::Network;
36
37 use bitcoin_hashes::sha256::Hash as Sha256;
38 use bitcoin_hashes::Hash;
39
40 use secp256k1::{Secp256k1, Message};
41 use secp256k1::key::{PublicKey,SecretKey};
42
43 use std::collections::{BTreeSet, HashMap, HashSet};
44 use std::default::Default;
45 use std::sync::{Arc, Mutex};
46 use std::sync::atomic::Ordering;
47 use std::{mem, io};
48
49 use rand::{thread_rng, Rng};
50
51 use ln::functional_test_utils::*;
52
53 #[test]
54 fn test_insane_channel_opens() {
55         // Stand up a network of 2 nodes
56         let chanmon_cfgs = create_chanmon_cfgs(2);
57         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
58         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
59         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
60
61         // Instantiate channel parameters where we push the maximum msats given our
62         // funding satoshis
63         let channel_value_sat = 31337; // same as funding satoshis
64         let channel_reserve_satoshis = Channel::<EnforcingChannelKeys>::get_our_channel_reserve_satoshis(channel_value_sat);
65         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
66
67         // Have node0 initiate a channel to node1 with aforementioned parameters
68         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
69
70         // Extract the channel open message from node0 to node1
71         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
72
73         // Test helper that asserts we get the correct error string given a mutator
74         // that supposedly makes the channel open message insane
75         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
76                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::supported(), &message_mutator(open_channel_message.clone()));
77                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
78                 assert_eq!(msg_events.len(), 1);
79                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
80                         match action {
81                                 &ErrorAction::SendErrorMessage { .. } => {
82                                         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), expected_error_str.to_string(), 1);
83                                 },
84                                 _ => panic!("unexpected event!"),
85                         }
86                 } else { assert!(false); }
87         };
88
89         use ln::channel::MAX_FUNDING_SATOSHIS;
90         use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
91
92         // Test all mutations that would make the channel open message insane
93         insane_open_helper("funding value > 2^24", |mut msg| { msg.funding_satoshis = MAX_FUNDING_SATOSHIS; msg });
94
95         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
96
97         insane_open_helper("push_msat larger than funding value", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
98
99         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
100
101         insane_open_helper("Bogus; channel reserve is less than dust limit", |mut msg| { msg.dust_limit_satoshis = msg.channel_reserve_satoshis + 1; msg });
102
103         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 });
104
105         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 });
106
107         insane_open_helper("0 max_accpted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
108
109         insane_open_helper("max_accpted_htlcs > 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
110 }
111
112 #[test]
113 fn test_async_inbound_update_fee() {
114         let chanmon_cfgs = create_chanmon_cfgs(2);
115         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
116         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
117         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
118         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
119         let channel_id = chan.2;
120
121         // balancing
122         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
123
124         // A                                        B
125         // update_fee                            ->
126         // send (1) commitment_signed            -.
127         //                                       <- update_add_htlc/commitment_signed
128         // send (2) RAA (awaiting remote revoke) -.
129         // (1) commitment_signed is delivered    ->
130         //                                       .- send (3) RAA (awaiting remote revoke)
131         // (2) RAA is delivered                  ->
132         //                                       .- send (4) commitment_signed
133         //                                       <- (3) RAA is delivered
134         // send (5) commitment_signed            -.
135         //                                       <- (4) commitment_signed is delivered
136         // send (6) RAA                          -.
137         // (5) commitment_signed is delivered    ->
138         //                                       <- RAA
139         // (6) RAA is delivered                  ->
140
141         // First nodes[0] generates an update_fee
142         nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
143         check_added_monitors!(nodes[0], 1);
144
145         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
146         assert_eq!(events_0.len(), 1);
147         let (update_msg, commitment_signed) = match events_0[0] { // (1)
148                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
149                         (update_fee.as_ref(), commitment_signed)
150                 },
151                 _ => panic!("Unexpected event"),
152         };
153
154         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
155
156         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
157         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
158         nodes[1].node.send_payment(nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV).unwrap(), our_payment_hash).unwrap();
159         check_added_monitors!(nodes[1], 1);
160
161         let payment_event = {
162                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
163                 assert_eq!(events_1.len(), 1);
164                 SendEvent::from_event(events_1.remove(0))
165         };
166         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
167         assert_eq!(payment_event.msgs.len(), 1);
168
169         // ...now when the messages get delivered everyone should be happy
170         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
171         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
172         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
173         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
174         check_added_monitors!(nodes[0], 1);
175
176         // deliver(1), generate (3):
177         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
178         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
179         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
180         check_added_monitors!(nodes[1], 1);
181
182         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
183         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
184         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
185         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
186         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
187         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
188         assert!(bs_update.update_fee.is_none()); // (4)
189         check_added_monitors!(nodes[1], 1);
190
191         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
192         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
193         assert!(as_update.update_add_htlcs.is_empty()); // (5)
194         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
195         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
196         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
197         assert!(as_update.update_fee.is_none()); // (5)
198         check_added_monitors!(nodes[0], 1);
199
200         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
201         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
202         // only (6) so get_event_msg's assert(len == 1) passes
203         check_added_monitors!(nodes[0], 1);
204
205         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
206         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
207         check_added_monitors!(nodes[1], 1);
208
209         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
210         check_added_monitors!(nodes[0], 1);
211
212         let events_2 = nodes[0].node.get_and_clear_pending_events();
213         assert_eq!(events_2.len(), 1);
214         match events_2[0] {
215                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
216                 _ => panic!("Unexpected event"),
217         }
218
219         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
220         check_added_monitors!(nodes[1], 1);
221 }
222
223 #[test]
224 fn test_update_fee_unordered_raa() {
225         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
226         // crash in an earlier version of the update_fee patch)
227         let chanmon_cfgs = create_chanmon_cfgs(2);
228         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
229         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
230         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
231         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
232         let channel_id = chan.2;
233
234         // balancing
235         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
236
237         // First nodes[0] generates an update_fee
238         nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
239         check_added_monitors!(nodes[0], 1);
240
241         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
242         assert_eq!(events_0.len(), 1);
243         let update_msg = match events_0[0] { // (1)
244                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
245                         update_fee.as_ref()
246                 },
247                 _ => panic!("Unexpected event"),
248         };
249
250         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
251
252         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
253         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
254         nodes[1].node.send_payment(nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV).unwrap(), our_payment_hash).unwrap();
255         check_added_monitors!(nodes[1], 1);
256
257         let payment_event = {
258                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
259                 assert_eq!(events_1.len(), 1);
260                 SendEvent::from_event(events_1.remove(0))
261         };
262         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
263         assert_eq!(payment_event.msgs.len(), 1);
264
265         // ...now when the messages get delivered everyone should be happy
266         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
267         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
268         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
269         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
270         check_added_monitors!(nodes[0], 1);
271
272         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
273         check_added_monitors!(nodes[1], 1);
274
275         // We can't continue, sadly, because our (1) now has a bogus signature
276 }
277
278 #[test]
279 fn test_multi_flight_update_fee() {
280         let chanmon_cfgs = create_chanmon_cfgs(2);
281         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
282         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
283         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
284         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
285         let channel_id = chan.2;
286
287         // A                                        B
288         // update_fee/commitment_signed          ->
289         //                                       .- send (1) RAA and (2) commitment_signed
290         // update_fee (never committed)          ->
291         // (3) update_fee                        ->
292         // We have to manually generate the above update_fee, it is allowed by the protocol but we
293         // don't track which updates correspond to which revoke_and_ack responses so we're in
294         // AwaitingRAA mode and will not generate the update_fee yet.
295         //                                       <- (1) RAA delivered
296         // (3) is generated and send (4) CS      -.
297         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
298         // know the per_commitment_point to use for it.
299         //                                       <- (2) commitment_signed delivered
300         // revoke_and_ack                        ->
301         //                                          B should send no response here
302         // (4) commitment_signed delivered       ->
303         //                                       <- RAA/commitment_signed delivered
304         // revoke_and_ack                        ->
305
306         // First nodes[0] generates an update_fee
307         let initial_feerate = get_feerate!(nodes[0], channel_id);
308         nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
309         check_added_monitors!(nodes[0], 1);
310
311         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
312         assert_eq!(events_0.len(), 1);
313         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
314                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
315                         (update_fee.as_ref().unwrap(), commitment_signed)
316                 },
317                 _ => panic!("Unexpected event"),
318         };
319
320         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
321         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
322         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
323         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
324         check_added_monitors!(nodes[1], 1);
325
326         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
327         // transaction:
328         nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
329         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
330         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
331
332         // Create the (3) update_fee message that nodes[0] will generate before it does...
333         let mut update_msg_2 = msgs::UpdateFee {
334                 channel_id: update_msg_1.channel_id.clone(),
335                 feerate_per_kw: (initial_feerate + 30) as u32,
336         };
337
338         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
339
340         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
341         // Deliver (3)
342         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
343
344         // Deliver (1), generating (3) and (4)
345         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
346         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
347         check_added_monitors!(nodes[0], 1);
348         assert!(as_second_update.update_add_htlcs.is_empty());
349         assert!(as_second_update.update_fulfill_htlcs.is_empty());
350         assert!(as_second_update.update_fail_htlcs.is_empty());
351         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
352         // Check that the update_fee newly generated matches what we delivered:
353         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
354         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
355
356         // Deliver (2) commitment_signed
357         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
358         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
359         check_added_monitors!(nodes[0], 1);
360         // No commitment_signed so get_event_msg's assert(len == 1) passes
361
362         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
363         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
364         check_added_monitors!(nodes[1], 1);
365
366         // Delever (4)
367         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
368         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
369         check_added_monitors!(nodes[1], 1);
370
371         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
372         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
373         check_added_monitors!(nodes[0], 1);
374
375         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
376         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
377         // No commitment_signed so get_event_msg's assert(len == 1) passes
378         check_added_monitors!(nodes[0], 1);
379
380         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
381         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
382         check_added_monitors!(nodes[1], 1);
383 }
384
385 #[test]
386 fn test_1_conf_open() {
387         // Previously, if the minium_depth config was set to 1, we'd never send a funding_locked. This
388         // tests that we properly send one in that case.
389         let mut alice_config = UserConfig::default();
390         alice_config.own_channel_config.minimum_depth = 1;
391         alice_config.channel_options.announced_channel = true;
392         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
393         let mut bob_config = UserConfig::default();
394         bob_config.own_channel_config.minimum_depth = 1;
395         bob_config.channel_options.announced_channel = true;
396         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
397         let chanmon_cfgs = create_chanmon_cfgs(2);
398         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
399         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(alice_config), Some(bob_config)]);
400         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
401
402         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::supported(), InitFeatures::supported());
403         assert!(nodes[0].chain_monitor.does_match_tx(&tx));
404         assert!(nodes[1].chain_monitor.does_match_tx(&tx));
405
406         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
407         nodes[1].block_notifier.block_connected_checked(&header, 1, &[&tx; 1], &[tx.version; 1]);
408         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()));
409
410         nodes[0].block_notifier.block_connected_checked(&header, 1, &[&tx; 1], &[tx.version; 1]);
411         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
412         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
413
414         for node in nodes {
415                 assert!(node.router.handle_channel_announcement(&announcement).unwrap());
416                 node.router.handle_channel_update(&as_update).unwrap();
417                 node.router.handle_channel_update(&bs_update).unwrap();
418         }
419 }
420
421 fn do_test_sanity_on_in_flight_opens(steps: u8) {
422         // Previously, we had issues deserializing channels when we hadn't connected the first block
423         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
424         // serialization round-trips and simply do steps towards opening a channel and then drop the
425         // Node objects.
426
427         let chanmon_cfgs = create_chanmon_cfgs(2);
428         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
429         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
430         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
431
432         if steps & 0b1000_0000 != 0{
433                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
434                 nodes[0].block_notifier.block_connected_checked(&header, 1, &Vec::new(), &[0; 0]);
435                 nodes[1].block_notifier.block_connected_checked(&header, 1, &Vec::new(), &[0; 0]);
436         }
437
438         if steps & 0x0f == 0 { return; }
439         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
440         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
441
442         if steps & 0x0f == 1 { return; }
443         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::supported(), &open_channel);
444         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
445
446         if steps & 0x0f == 2 { return; }
447         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::supported(), &accept_channel);
448
449         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
450
451         if steps & 0x0f == 3 { return; }
452         {
453                 nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
454                 let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
455                 assert_eq!(added_monitors.len(), 1);
456                 assert_eq!(added_monitors[0].0, funding_output);
457                 added_monitors.clear();
458         }
459         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
460
461         if steps & 0x0f == 4 { return; }
462         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
463         {
464                 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
465                 assert_eq!(added_monitors.len(), 1);
466                 assert_eq!(added_monitors[0].0, funding_output);
467                 added_monitors.clear();
468         }
469         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
470
471         if steps & 0x0f == 5 { return; }
472         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
473         {
474                 let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
475                 assert_eq!(added_monitors.len(), 1);
476                 assert_eq!(added_monitors[0].0, funding_output);
477                 added_monitors.clear();
478         }
479
480         let events_4 = nodes[0].node.get_and_clear_pending_events();
481         assert_eq!(events_4.len(), 1);
482         match events_4[0] {
483                 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
484                         assert_eq!(user_channel_id, 42);
485                         assert_eq!(*funding_txo, funding_output);
486                 },
487                 _ => panic!("Unexpected event"),
488         };
489
490         if steps & 0x0f == 6 { return; }
491         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx);
492
493         if steps & 0x0f == 7 { return; }
494         confirm_transaction(&nodes[0].block_notifier, &nodes[0].chain_monitor, &tx, tx.version);
495         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
496 }
497
498 #[test]
499 fn test_sanity_on_in_flight_opens() {
500         do_test_sanity_on_in_flight_opens(0);
501         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
502         do_test_sanity_on_in_flight_opens(1);
503         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
504         do_test_sanity_on_in_flight_opens(2);
505         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
506         do_test_sanity_on_in_flight_opens(3);
507         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
508         do_test_sanity_on_in_flight_opens(4);
509         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
510         do_test_sanity_on_in_flight_opens(5);
511         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
512         do_test_sanity_on_in_flight_opens(6);
513         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
514         do_test_sanity_on_in_flight_opens(7);
515         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
516         do_test_sanity_on_in_flight_opens(8);
517         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
518 }
519
520 #[test]
521 fn test_update_fee_vanilla() {
522         let chanmon_cfgs = create_chanmon_cfgs(2);
523         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
524         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
525         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
526         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
527         let channel_id = chan.2;
528
529         let feerate = get_feerate!(nodes[0], channel_id);
530         nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
531         check_added_monitors!(nodes[0], 1);
532
533         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
534         assert_eq!(events_0.len(), 1);
535         let (update_msg, commitment_signed) = match events_0[0] {
536                         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 } } => {
537                         (update_fee.as_ref(), commitment_signed)
538                 },
539                 _ => panic!("Unexpected event"),
540         };
541         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
542
543         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
544         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
545         check_added_monitors!(nodes[1], 1);
546
547         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
548         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
549         check_added_monitors!(nodes[0], 1);
550
551         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
552         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
553         // No commitment_signed so get_event_msg's assert(len == 1) passes
554         check_added_monitors!(nodes[0], 1);
555
556         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
557         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
558         check_added_monitors!(nodes[1], 1);
559 }
560
561 #[test]
562 fn test_update_fee_that_funder_cannot_afford() {
563         let chanmon_cfgs = create_chanmon_cfgs(2);
564         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
565         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
566         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
567         let channel_value = 1888;
568         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000, InitFeatures::supported(), InitFeatures::supported());
569         let channel_id = chan.2;
570
571         let feerate = 260;
572         nodes[0].node.update_fee(channel_id, feerate).unwrap();
573         check_added_monitors!(nodes[0], 1);
574         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
575
576         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
577
578         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
579
580         //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
581         //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
582         {
583                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
584
585                 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
586                 let num_htlcs = commitment_tx.output.len() - 2;
587                 let total_fee: u64 = feerate * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
588                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
589                 actual_fee = channel_value - actual_fee;
590                 assert_eq!(total_fee, actual_fee);
591         }
592
593         //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
594         //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
595         nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
596         check_added_monitors!(nodes[0], 1);
597
598         let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
599
600         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap());
601
602         //While producing the commitment_signed response after handling a received update_fee request the
603         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
604         //Should produce and error.
605         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed);
606         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
607         check_added_monitors!(nodes[1], 1);
608         check_closed_broadcast!(nodes[1], true);
609 }
610
611 #[test]
612 fn test_update_fee_with_fundee_update_add_htlc() {
613         let chanmon_cfgs = create_chanmon_cfgs(2);
614         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
615         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
616         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
617         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
618         let channel_id = chan.2;
619
620         // balancing
621         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
622
623         let feerate = get_feerate!(nodes[0], channel_id);
624         nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
625         check_added_monitors!(nodes[0], 1);
626
627         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
628         assert_eq!(events_0.len(), 1);
629         let (update_msg, commitment_signed) = match events_0[0] {
630                         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 } } => {
631                         (update_fee.as_ref(), commitment_signed)
632                 },
633                 _ => panic!("Unexpected event"),
634         };
635         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
636         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
637         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
638         check_added_monitors!(nodes[1], 1);
639
640         let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 800000, TEST_FINAL_CLTV).unwrap();
641
642         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
643
644         // nothing happens since node[1] is in AwaitingRemoteRevoke
645         nodes[1].node.send_payment(route, our_payment_hash).unwrap();
646         {
647                 let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
648                 assert_eq!(added_monitors.len(), 0);
649                 added_monitors.clear();
650         }
651         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
652         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
653         // node[1] has nothing to do
654
655         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
656         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
657         check_added_monitors!(nodes[0], 1);
658
659         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
660         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
661         // No commitment_signed so get_event_msg's assert(len == 1) passes
662         check_added_monitors!(nodes[0], 1);
663         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
664         check_added_monitors!(nodes[1], 1);
665         // AwaitingRemoteRevoke ends here
666
667         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
668         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
669         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
670         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
671         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
672         assert_eq!(commitment_update.update_fee.is_none(), true);
673
674         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
675         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
676         check_added_monitors!(nodes[0], 1);
677         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
678
679         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
680         check_added_monitors!(nodes[1], 1);
681         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
682
683         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
684         check_added_monitors!(nodes[1], 1);
685         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
686         // No commitment_signed so get_event_msg's assert(len == 1) passes
687
688         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
689         check_added_monitors!(nodes[0], 1);
690         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
691
692         expect_pending_htlcs_forwardable!(nodes[0]);
693
694         let events = nodes[0].node.get_and_clear_pending_events();
695         assert_eq!(events.len(), 1);
696         match events[0] {
697                 Event::PaymentReceived { .. } => { },
698                 _ => panic!("Unexpected event"),
699         };
700
701         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage, 800_000);
702
703         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000, 800_000);
704         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000, 800_000);
705         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
706 }
707
708 #[test]
709 fn test_update_fee() {
710         let chanmon_cfgs = create_chanmon_cfgs(2);
711         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
712         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
713         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
714         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
715         let channel_id = chan.2;
716
717         // A                                        B
718         // (1) update_fee/commitment_signed      ->
719         //                                       <- (2) revoke_and_ack
720         //                                       .- send (3) commitment_signed
721         // (4) update_fee/commitment_signed      ->
722         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
723         //                                       <- (3) commitment_signed delivered
724         // send (6) revoke_and_ack               -.
725         //                                       <- (5) deliver revoke_and_ack
726         // (6) deliver revoke_and_ack            ->
727         //                                       .- send (7) commitment_signed in response to (4)
728         //                                       <- (7) deliver commitment_signed
729         // revoke_and_ack                        ->
730
731         // Create and deliver (1)...
732         let feerate = get_feerate!(nodes[0], channel_id);
733         nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
734         check_added_monitors!(nodes[0], 1);
735
736         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
737         assert_eq!(events_0.len(), 1);
738         let (update_msg, commitment_signed) = match events_0[0] {
739                         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 } } => {
740                         (update_fee.as_ref(), commitment_signed)
741                 },
742                 _ => panic!("Unexpected event"),
743         };
744         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
745
746         // Generate (2) and (3):
747         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
748         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
749         check_added_monitors!(nodes[1], 1);
750
751         // Deliver (2):
752         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
753         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
754         check_added_monitors!(nodes[0], 1);
755
756         // Create and deliver (4)...
757         nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
758         check_added_monitors!(nodes[0], 1);
759         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
760         assert_eq!(events_0.len(), 1);
761         let (update_msg, commitment_signed) = match events_0[0] {
762                         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 } } => {
763                         (update_fee.as_ref(), commitment_signed)
764                 },
765                 _ => panic!("Unexpected event"),
766         };
767
768         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
769         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
770         check_added_monitors!(nodes[1], 1);
771         // ... creating (5)
772         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
773         // No commitment_signed so get_event_msg's assert(len == 1) passes
774
775         // Handle (3), creating (6):
776         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
777         check_added_monitors!(nodes[0], 1);
778         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
779         // No commitment_signed so get_event_msg's assert(len == 1) passes
780
781         // Deliver (5):
782         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
783         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
784         check_added_monitors!(nodes[0], 1);
785
786         // Deliver (6), creating (7):
787         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
788         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
789         assert!(commitment_update.update_add_htlcs.is_empty());
790         assert!(commitment_update.update_fulfill_htlcs.is_empty());
791         assert!(commitment_update.update_fail_htlcs.is_empty());
792         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
793         assert!(commitment_update.update_fee.is_none());
794         check_added_monitors!(nodes[1], 1);
795
796         // Deliver (7)
797         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
798         check_added_monitors!(nodes[0], 1);
799         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
800         // No commitment_signed so get_event_msg's assert(len == 1) passes
801
802         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
803         check_added_monitors!(nodes[1], 1);
804         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
805
806         assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
807         assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
808         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
809 }
810
811 #[test]
812 fn pre_funding_lock_shutdown_test() {
813         // Test sending a shutdown prior to funding_locked after funding generation
814         let chanmon_cfgs = create_chanmon_cfgs(2);
815         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
816         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
817         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
818         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0, InitFeatures::supported(), InitFeatures::supported());
819         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
820         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![tx.clone()]}, 1);
821         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![tx.clone()]}, 1);
822
823         nodes[0].node.close_channel(&OutPoint::new(tx.txid(), 0).to_channel_id()).unwrap();
824         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
825         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
826         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
827         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
828
829         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
830         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
831         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
832         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
833         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
834         assert!(node_0_none.is_none());
835
836         assert!(nodes[0].node.list_channels().is_empty());
837         assert!(nodes[1].node.list_channels().is_empty());
838 }
839
840 #[test]
841 fn updates_shutdown_wait() {
842         // Test sending a shutdown with outstanding updates pending
843         let chanmon_cfgs = create_chanmon_cfgs(3);
844         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
845         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
846         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
847         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
848         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
849         let route_1 = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
850         let route_2 = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
851
852         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
853
854         nodes[0].node.close_channel(&chan_1.2).unwrap();
855         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
856         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
857         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
858         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
859
860         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
861         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
862
863         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
864         if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route_1, payment_hash) {}
865         else { panic!("New sends should fail!") };
866         if let Err(APIError::ChannelUnavailable {..}) = nodes[1].node.send_payment(route_2, payment_hash) {}
867         else { panic!("New sends should fail!") };
868
869         assert!(nodes[2].node.claim_funds(our_payment_preimage, 100_000));
870         check_added_monitors!(nodes[2], 1);
871         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
872         assert!(updates.update_add_htlcs.is_empty());
873         assert!(updates.update_fail_htlcs.is_empty());
874         assert!(updates.update_fail_malformed_htlcs.is_empty());
875         assert!(updates.update_fee.is_none());
876         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
877         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
878         check_added_monitors!(nodes[1], 1);
879         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
880         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
881
882         assert!(updates_2.update_add_htlcs.is_empty());
883         assert!(updates_2.update_fail_htlcs.is_empty());
884         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
885         assert!(updates_2.update_fee.is_none());
886         assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
887         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
888         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
889
890         let events = nodes[0].node.get_and_clear_pending_events();
891         assert_eq!(events.len(), 1);
892         match events[0] {
893                 Event::PaymentSent { ref payment_preimage } => {
894                         assert_eq!(our_payment_preimage, *payment_preimage);
895                 },
896                 _ => panic!("Unexpected event"),
897         }
898
899         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
900         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
901         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
902         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
903         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
904         assert!(node_0_none.is_none());
905
906         assert!(nodes[0].node.list_channels().is_empty());
907
908         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
909         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
910         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
911         assert!(nodes[1].node.list_channels().is_empty());
912         assert!(nodes[2].node.list_channels().is_empty());
913 }
914
915 #[test]
916 fn htlc_fail_async_shutdown() {
917         // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
918         let chanmon_cfgs = create_chanmon_cfgs(3);
919         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
920         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
921         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
922         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
923         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
924
925         let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
926         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
927         nodes[0].node.send_payment(route, our_payment_hash).unwrap();
928         check_added_monitors!(nodes[0], 1);
929         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
930         assert_eq!(updates.update_add_htlcs.len(), 1);
931         assert!(updates.update_fulfill_htlcs.is_empty());
932         assert!(updates.update_fail_htlcs.is_empty());
933         assert!(updates.update_fail_malformed_htlcs.is_empty());
934         assert!(updates.update_fee.is_none());
935
936         nodes[1].node.close_channel(&chan_1.2).unwrap();
937         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
938         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
939         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
940
941         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
942         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
943         check_added_monitors!(nodes[1], 1);
944         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
945         commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
946
947         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
948         assert!(updates_2.update_add_htlcs.is_empty());
949         assert!(updates_2.update_fulfill_htlcs.is_empty());
950         assert_eq!(updates_2.update_fail_htlcs.len(), 1);
951         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
952         assert!(updates_2.update_fee.is_none());
953
954         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]);
955         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
956
957         let events = nodes[0].node.get_and_clear_pending_events();
958         assert_eq!(events.len(), 1);
959         match events[0] {
960                 Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } => {
961                         assert_eq!(our_payment_hash, *payment_hash);
962                         assert!(!rejected_by_dest);
963                 },
964                 _ => panic!("Unexpected event"),
965         }
966
967         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
968         assert_eq!(msg_events.len(), 2);
969         let node_0_closing_signed = match msg_events[0] {
970                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
971                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
972                         (*msg).clone()
973                 },
974                 _ => panic!("Unexpected event"),
975         };
976         match msg_events[1] {
977                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
978                         assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
979                 },
980                 _ => panic!("Unexpected event"),
981         }
982
983         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
984         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
985         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
986         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
987         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
988         assert!(node_0_none.is_none());
989
990         assert!(nodes[0].node.list_channels().is_empty());
991
992         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
993         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
994         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
995         assert!(nodes[1].node.list_channels().is_empty());
996         assert!(nodes[2].node.list_channels().is_empty());
997 }
998
999 fn do_test_shutdown_rebroadcast(recv_count: u8) {
1000         // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
1001         // messages delivered prior to disconnect
1002         let chanmon_cfgs = create_chanmon_cfgs(3);
1003         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1004         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1005         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1006         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
1007         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
1008
1009         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
1010
1011         nodes[1].node.close_channel(&chan_1.2).unwrap();
1012         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1013         if recv_count > 0 {
1014                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
1015                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1016                 if recv_count > 1 {
1017                         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
1018                 }
1019         }
1020
1021         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1022         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1023
1024         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1025         let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1026         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1027         let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1028
1029         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish);
1030         let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1031         assert!(node_1_shutdown == node_1_2nd_shutdown);
1032
1033         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish);
1034         let node_0_2nd_shutdown = if recv_count > 0 {
1035                 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1036                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
1037                 node_0_2nd_shutdown
1038         } else {
1039                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1040                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
1041                 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
1042         };
1043         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown);
1044
1045         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1046         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1047
1048         assert!(nodes[2].node.claim_funds(our_payment_preimage, 100_000));
1049         check_added_monitors!(nodes[2], 1);
1050         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1051         assert!(updates.update_add_htlcs.is_empty());
1052         assert!(updates.update_fail_htlcs.is_empty());
1053         assert!(updates.update_fail_malformed_htlcs.is_empty());
1054         assert!(updates.update_fee.is_none());
1055         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
1056         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
1057         check_added_monitors!(nodes[1], 1);
1058         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1059         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
1060
1061         assert!(updates_2.update_add_htlcs.is_empty());
1062         assert!(updates_2.update_fail_htlcs.is_empty());
1063         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
1064         assert!(updates_2.update_fee.is_none());
1065         assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
1066         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
1067         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
1068
1069         let events = nodes[0].node.get_and_clear_pending_events();
1070         assert_eq!(events.len(), 1);
1071         match events[0] {
1072                 Event::PaymentSent { ref payment_preimage } => {
1073                         assert_eq!(our_payment_preimage, *payment_preimage);
1074                 },
1075                 _ => panic!("Unexpected event"),
1076         }
1077
1078         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1079         if recv_count > 0 {
1080                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
1081                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1082                 assert!(node_1_closing_signed.is_some());
1083         }
1084
1085         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1086         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1087
1088         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1089         let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1090         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1091         if recv_count == 0 {
1092                 // If all closing_signeds weren't delivered we can just resume where we left off...
1093                 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1094
1095                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish);
1096                 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1097                 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
1098
1099                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1100                 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1101                 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
1102
1103                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown);
1104                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1105
1106                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown);
1107                 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1108                 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
1109
1110                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed);
1111                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1112                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
1113                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1114                 assert!(node_0_none.is_none());
1115         } else {
1116                 // If one node, however, received + responded with an identical closing_signed we end
1117                 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
1118                 // There isn't really anything better we can do simply, but in the future we might
1119                 // explore storing a set of recently-closed channels that got disconnected during
1120                 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
1121                 // give our counterparty enough time to (potentially) broadcast a cooperative closing
1122                 // transaction.
1123                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1124
1125                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1126                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1127                 assert_eq!(msg_events.len(), 1);
1128                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
1129                         match action {
1130                                 &ErrorAction::SendErrorMessage { ref msg } => {
1131                                         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
1132                                         assert_eq!(msg.channel_id, chan_1.2);
1133                                 },
1134                                 _ => panic!("Unexpected event!"),
1135                         }
1136                 } else { panic!("Needed SendErrorMessage close"); }
1137
1138                 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
1139                 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
1140                 // closing_signed so we do it ourselves
1141                 check_closed_broadcast!(nodes[0], false);
1142                 check_added_monitors!(nodes[0], 1);
1143         }
1144
1145         assert!(nodes[0].node.list_channels().is_empty());
1146
1147         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1148         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1149         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1150         assert!(nodes[1].node.list_channels().is_empty());
1151         assert!(nodes[2].node.list_channels().is_empty());
1152 }
1153
1154 #[test]
1155 fn test_shutdown_rebroadcast() {
1156         do_test_shutdown_rebroadcast(0);
1157         do_test_shutdown_rebroadcast(1);
1158         do_test_shutdown_rebroadcast(2);
1159 }
1160
1161 #[test]
1162 fn fake_network_test() {
1163         // Simple test which builds a network of ChannelManagers, connects them to each other, and
1164         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
1165         let chanmon_cfgs = create_chanmon_cfgs(4);
1166         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1167         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1168         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1169
1170         // Create some initial channels
1171         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
1172         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
1173         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::supported(), InitFeatures::supported());
1174
1175         // Rebalance the network a bit by relaying one payment through all the channels...
1176         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1177         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1178         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1179         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1180
1181         // Send some more payments
1182         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000, 1_000_000);
1183         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000, 1_000_000);
1184         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000, 1_000_000);
1185
1186         // Test failure packets
1187         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1188         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1189
1190         // Add a new channel that skips 3
1191         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::supported(), InitFeatures::supported());
1192
1193         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000, 1_000_000);
1194         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000, 1_000_000);
1195         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1196         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1197         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1198         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1199         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1200
1201         // Do some rebalance loop payments, simultaneously
1202         let mut hops = Vec::with_capacity(3);
1203         hops.push(RouteHop {
1204                 pubkey: nodes[2].node.get_our_node_id(),
1205                 node_features: NodeFeatures::empty(),
1206                 short_channel_id: chan_2.0.contents.short_channel_id,
1207                 channel_features: ChannelFeatures::empty(),
1208                 fee_msat: 0,
1209                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1210         });
1211         hops.push(RouteHop {
1212                 pubkey: nodes[3].node.get_our_node_id(),
1213                 node_features: NodeFeatures::empty(),
1214                 short_channel_id: chan_3.0.contents.short_channel_id,
1215                 channel_features: ChannelFeatures::empty(),
1216                 fee_msat: 0,
1217                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1218         });
1219         hops.push(RouteHop {
1220                 pubkey: nodes[1].node.get_our_node_id(),
1221                 node_features: NodeFeatures::empty(),
1222                 short_channel_id: chan_4.0.contents.short_channel_id,
1223                 channel_features: ChannelFeatures::empty(),
1224                 fee_msat: 1000000,
1225                 cltv_expiry_delta: TEST_FINAL_CLTV,
1226         });
1227         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;
1228         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;
1229         let payment_preimage_1 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1230
1231         let mut hops = Vec::with_capacity(3);
1232         hops.push(RouteHop {
1233                 pubkey: nodes[3].node.get_our_node_id(),
1234                 node_features: NodeFeatures::empty(),
1235                 short_channel_id: chan_4.0.contents.short_channel_id,
1236                 channel_features: ChannelFeatures::empty(),
1237                 fee_msat: 0,
1238                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1239         });
1240         hops.push(RouteHop {
1241                 pubkey: nodes[2].node.get_our_node_id(),
1242                 node_features: NodeFeatures::empty(),
1243                 short_channel_id: chan_3.0.contents.short_channel_id,
1244                 channel_features: ChannelFeatures::empty(),
1245                 fee_msat: 0,
1246                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1247         });
1248         hops.push(RouteHop {
1249                 pubkey: nodes[1].node.get_our_node_id(),
1250                 node_features: NodeFeatures::empty(),
1251                 short_channel_id: chan_2.0.contents.short_channel_id,
1252                 channel_features: ChannelFeatures::empty(),
1253                 fee_msat: 1000000,
1254                 cltv_expiry_delta: TEST_FINAL_CLTV,
1255         });
1256         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;
1257         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;
1258         let payment_hash_2 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1259
1260         // Claim the rebalances...
1261         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1262         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1, 1_000_000);
1263
1264         // Add a duplicate new channel from 2 to 4
1265         let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::supported(), InitFeatures::supported());
1266
1267         // Send some payments across both channels
1268         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1269         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1270         let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1271
1272
1273         route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1274         let events = nodes[0].node.get_and_clear_pending_msg_events();
1275         assert_eq!(events.len(), 0);
1276         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);
1277
1278         //TODO: Test that routes work again here as we've been notified that the channel is full
1279
1280         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3, 3_000_000);
1281         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4, 3_000_000);
1282         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5, 3_000_000);
1283
1284         // Close down the channels...
1285         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1286         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1287         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1288         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1289         close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1290 }
1291
1292 #[test]
1293 fn holding_cell_htlc_counting() {
1294         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1295         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1296         // commitment dance rounds.
1297         let chanmon_cfgs = create_chanmon_cfgs(3);
1298         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1299         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1300         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1301         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
1302         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
1303
1304         let mut payments = Vec::new();
1305         for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1306                 let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
1307                 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1308                 nodes[1].node.send_payment(route, payment_hash).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 route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
1322         let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
1323         if let APIError::ChannelUnavailable { err } = nodes[1].node.send_payment(route, payment_hash_1).unwrap_err() {
1324                 assert_eq!(err, "Cannot push more than their max accepted HTLCs");
1325         } else { panic!("Unexpected event"); }
1326         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1327         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1328
1329         // This should also be true if we try to forward a payment.
1330         let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
1331         let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
1332         nodes[0].node.send_payment(route, payment_hash_2).unwrap();
1333         check_added_monitors!(nodes[0], 1);
1334
1335         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1336         assert_eq!(events.len(), 1);
1337         let payment_event = SendEvent::from_event(events.pop().unwrap());
1338         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1339
1340         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1341         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1342         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1343         // fails), the second will process the resulting failure and fail the HTLC backward.
1344         expect_pending_htlcs_forwardable!(nodes[1]);
1345         expect_pending_htlcs_forwardable!(nodes[1]);
1346         check_added_monitors!(nodes[1], 1);
1347
1348         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1349         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1350         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1351
1352         let events = nodes[0].node.get_and_clear_pending_msg_events();
1353         assert_eq!(events.len(), 1);
1354         match events[0] {
1355                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
1356                         assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
1357                 },
1358                 _ => panic!("Unexpected event"),
1359         }
1360
1361         let events = nodes[0].node.get_and_clear_pending_events();
1362         assert_eq!(events.len(), 1);
1363         match events[0] {
1364                 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
1365                         assert_eq!(payment_hash, payment_hash_2);
1366                         assert!(!rejected_by_dest);
1367                 },
1368                 _ => panic!("Unexpected event"),
1369         }
1370
1371         // Now forward all the pending HTLCs and claim them back
1372         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1373         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1374         check_added_monitors!(nodes[2], 1);
1375
1376         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1377         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1378         check_added_monitors!(nodes[1], 1);
1379         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1380
1381         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1382         check_added_monitors!(nodes[1], 1);
1383         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1384
1385         for ref update in as_updates.update_add_htlcs.iter() {
1386                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1387         }
1388         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1389         check_added_monitors!(nodes[2], 1);
1390         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1391         check_added_monitors!(nodes[2], 1);
1392         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1393
1394         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1395         check_added_monitors!(nodes[1], 1);
1396         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1397         check_added_monitors!(nodes[1], 1);
1398         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1399
1400         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1401         check_added_monitors!(nodes[2], 1);
1402
1403         expect_pending_htlcs_forwardable!(nodes[2]);
1404
1405         let events = nodes[2].node.get_and_clear_pending_events();
1406         assert_eq!(events.len(), payments.len());
1407         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1408                 match event {
1409                         &Event::PaymentReceived { ref payment_hash, .. } => {
1410                                 assert_eq!(*payment_hash, *hash);
1411                         },
1412                         _ => panic!("Unexpected event"),
1413                 };
1414         }
1415
1416         for (preimage, _) in payments.drain(..) {
1417                 claim_payment(&nodes[1], &[&nodes[2]], preimage, 100_000);
1418         }
1419
1420         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000, 1_000_000);
1421 }
1422
1423 #[test]
1424 fn duplicate_htlc_test() {
1425         // Test that we accept duplicate payment_hash HTLCs across the network and that
1426         // claiming/failing them are all separate and don't affect each other
1427         let chanmon_cfgs = create_chanmon_cfgs(6);
1428         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1429         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1430         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1431
1432         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1433         create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::supported(), InitFeatures::supported());
1434         create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::supported(), InitFeatures::supported());
1435         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::supported(), InitFeatures::supported());
1436         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::supported(), InitFeatures::supported());
1437         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::supported(), InitFeatures::supported());
1438
1439         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1440
1441         *nodes[0].network_payment_count.borrow_mut() -= 1;
1442         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1443
1444         *nodes[0].network_payment_count.borrow_mut() -= 1;
1445         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1446
1447         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage, 1_000_000);
1448         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1449         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage, 1_000_000);
1450 }
1451
1452 #[test]
1453 fn test_duplicate_htlc_different_direction_onchain() {
1454         // Test that ChannelMonitor doesn't generate 2 preimage txn
1455         // when we have 2 HTLCs with same preimage that go across a node
1456         // in opposite directions.
1457         let chanmon_cfgs = create_chanmon_cfgs(2);
1458         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1459         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1460         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1461
1462         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
1463
1464         // balancing
1465         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
1466
1467         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1468
1469         let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 800_000, TEST_FINAL_CLTV).unwrap();
1470         send_along_route_with_hash(&nodes[1], route, &vec!(&nodes[0])[..], 800_000, payment_hash);
1471
1472         // Provide preimage to node 0 by claiming payment
1473         nodes[0].node.claim_funds(payment_preimage, 800_000);
1474         check_added_monitors!(nodes[0], 1);
1475
1476         // Broadcast node 1 commitment txn
1477         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1478
1479         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1480         let mut has_both_htlcs = 0; // check htlcs match ones committed
1481         for outp in remote_txn[0].output.iter() {
1482                 if outp.value == 800_000 / 1000 {
1483                         has_both_htlcs += 1;
1484                 } else if outp.value == 900_000 / 1000 {
1485                         has_both_htlcs += 1;
1486                 }
1487         }
1488         assert_eq!(has_both_htlcs, 2);
1489
1490         let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1491         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
1492         check_added_monitors!(nodes[0], 1);
1493
1494         // Check we only broadcast 1 timeout tx
1495         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1496         let htlc_pair = if claim_txn[0].output[0].value == 800_000 / 1000 { (claim_txn[0].clone(), claim_txn[1].clone()) } else { (claim_txn[1].clone(), claim_txn[0].clone()) };
1497         assert_eq!(claim_txn.len(), 5);
1498         check_spends!(claim_txn[2], chan_1.3);
1499         check_spends!(claim_txn[3], claim_txn[2]);
1500         assert_eq!(htlc_pair.0.input.len(), 1);
1501         assert_eq!(htlc_pair.0.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1502         check_spends!(htlc_pair.0, remote_txn[0]);
1503         assert_eq!(htlc_pair.1.input.len(), 1);
1504         assert_eq!(htlc_pair.1.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1505         check_spends!(htlc_pair.1, remote_txn[0]);
1506
1507         let events = nodes[0].node.get_and_clear_pending_msg_events();
1508         assert_eq!(events.len(), 2);
1509         for e in events {
1510                 match e {
1511                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1512                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
1513                                 assert!(update_add_htlcs.is_empty());
1514                                 assert!(update_fail_htlcs.is_empty());
1515                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1516                                 assert!(update_fail_malformed_htlcs.is_empty());
1517                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1518                         },
1519                         _ => panic!("Unexpected event"),
1520                 }
1521         }
1522 }
1523
1524 fn do_channel_reserve_test(test_recv: bool) {
1525
1526         let chanmon_cfgs = create_chanmon_cfgs(3);
1527         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1528         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1529         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1530         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1900, 1001, InitFeatures::supported(), InitFeatures::supported());
1531         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1900, 1001, InitFeatures::supported(), InitFeatures::supported());
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 route = nodes[0].router.get_route(&nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV).unwrap();
1542                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1543                         (route, payment_hash, payment_preimage)
1544                 }}
1545         };
1546
1547         macro_rules! expect_forward {
1548                 ($node: expr) => {{
1549                         let mut events = $node.node.get_and_clear_pending_msg_events();
1550                         assert_eq!(events.len(), 1);
1551                         check_added_monitors!($node, 1);
1552                         let payment_event = SendEvent::from_event(events.remove(0));
1553                         payment_event
1554                 }}
1555         }
1556
1557         let feemsat = 239; // somehow we know?
1558         let total_fee_msat = (nodes.len() - 2) as u64 * 239;
1559
1560         let recv_value_0 = stat01.their_max_htlc_value_in_flight_msat - total_fee_msat;
1561
1562         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1563         {
1564                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
1565                 assert!(route.hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1566                 let err = nodes[0].node.send_payment(route, our_payment_hash).err().unwrap();
1567                 match err {
1568                         APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over the max HTLC value in flight our peer will accept"),
1569                         _ => panic!("Unknown error variants"),
1570                 }
1571                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1572                 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);
1573         }
1574
1575         let mut htlc_id = 0;
1576         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1577         // nodes[0]'s wealth
1578         loop {
1579                 let amt_msat = recv_value_0 + total_fee_msat;
1580                 if stat01.value_to_self_msat - amt_msat < stat01.channel_reserve_msat {
1581                         break;
1582                 }
1583                 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0, recv_value_0);
1584                 htlc_id += 1;
1585
1586                 let (stat01_, stat11_, stat12_, stat22_) = (
1587                         get_channel_value_stat!(nodes[0], chan_1.2),
1588                         get_channel_value_stat!(nodes[1], chan_1.2),
1589                         get_channel_value_stat!(nodes[1], chan_2.2),
1590                         get_channel_value_stat!(nodes[2], chan_2.2),
1591                 );
1592
1593                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1594                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1595                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1596                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1597                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1598         }
1599
1600         {
1601                 let recv_value = stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat;
1602                 // attempt to get channel_reserve violation
1603                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value + 1);
1604                 let err = nodes[0].node.send_payment(route.clone(), our_payment_hash).err().unwrap();
1605                 match err {
1606                         APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over their reserve value"),
1607                         _ => panic!("Unknown error variants"),
1608                 }
1609                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1610                 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us over their reserve value".to_string(), 1);
1611         }
1612
1613         // adding pending output
1614         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat)/2;
1615         let amt_msat_1 = recv_value_1 + total_fee_msat;
1616
1617         let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
1618         let payment_event_1 = {
1619                 nodes[0].node.send_payment(route_1, our_payment_hash_1).unwrap();
1620                 check_added_monitors!(nodes[0], 1);
1621
1622                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1623                 assert_eq!(events.len(), 1);
1624                 SendEvent::from_event(events.remove(0))
1625         };
1626         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1627
1628         // channel reserve test with htlc pending output > 0
1629         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat;
1630         {
1631                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
1632                 match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
1633                         APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over their reserve value"),
1634                         _ => panic!("Unknown error variants"),
1635                 }
1636                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1637                 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us over their reserve value".to_string(), 2);
1638         }
1639
1640         {
1641                 // test channel_reserve test on nodes[1] side
1642                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
1643
1644                 // Need to manually create update_add_htlc message to go around the channel reserve check in send_htlc()
1645                 let secp_ctx = Secp256k1::new();
1646                 let session_priv = SecretKey::from_slice(&{
1647                         let mut session_key = [0; 32];
1648                         let mut rng = thread_rng();
1649                         rng.fill_bytes(&mut session_key);
1650                         session_key
1651                 }).expect("RNG is bad!");
1652
1653                 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1654                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
1655                 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
1656                 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
1657                 let msg = msgs::UpdateAddHTLC {
1658                         channel_id: chan_1.2,
1659                         htlc_id,
1660                         amount_msat: htlc_msat,
1661                         payment_hash: our_payment_hash,
1662                         cltv_expiry: htlc_cltv,
1663                         onion_routing_packet: onion_packet,
1664                 };
1665
1666                 if test_recv {
1667                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1668                         // If we send a garbage message, the channel should get closed, making the rest of this test case fail.
1669                         assert_eq!(nodes[1].node.list_channels().len(), 1);
1670                         assert_eq!(nodes[1].node.list_channels().len(), 1);
1671                         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1672                         assert_eq!(err_msg.data, "Remote HTLC add would put them over their reserve value");
1673                         check_added_monitors!(nodes[1], 1);
1674                         return;
1675                 }
1676         }
1677
1678         // split the rest to test holding cell
1679         let recv_value_21 = recv_value_2/2;
1680         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat;
1681         {
1682                 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1683                 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);
1684         }
1685
1686         // now see if they go through on both sides
1687         let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
1688         // but this will stuck in the holding cell
1689         nodes[0].node.send_payment(route_21, our_payment_hash_21).unwrap();
1690         check_added_monitors!(nodes[0], 0);
1691         let events = nodes[0].node.get_and_clear_pending_events();
1692         assert_eq!(events.len(), 0);
1693
1694         // test with outbound holding cell amount > 0
1695         {
1696                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
1697                 match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
1698                         APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over their reserve value"),
1699                         _ => panic!("Unknown error variants"),
1700                 }
1701                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1702                 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us over their reserve value".to_string(), 3);
1703         }
1704
1705         let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
1706         // this will also stuck in the holding cell
1707         nodes[0].node.send_payment(route_22, our_payment_hash_22).unwrap();
1708         check_added_monitors!(nodes[0], 0);
1709         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1710         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1711
1712         // flush the pending htlc
1713         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1714         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1715         check_added_monitors!(nodes[1], 1);
1716
1717         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1718         check_added_monitors!(nodes[0], 1);
1719         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1720
1721         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1722         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1723         // No commitment_signed so get_event_msg's assert(len == 1) passes
1724         check_added_monitors!(nodes[0], 1);
1725
1726         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1727         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1728         check_added_monitors!(nodes[1], 1);
1729
1730         expect_pending_htlcs_forwardable!(nodes[1]);
1731
1732         let ref payment_event_11 = expect_forward!(nodes[1]);
1733         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1734         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1735
1736         expect_pending_htlcs_forwardable!(nodes[2]);
1737         expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
1738
1739         // flush the htlcs in the holding cell
1740         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1741         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1742         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1743         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1744         expect_pending_htlcs_forwardable!(nodes[1]);
1745
1746         let ref payment_event_3 = expect_forward!(nodes[1]);
1747         assert_eq!(payment_event_3.msgs.len(), 2);
1748         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1749         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1750
1751         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1752         expect_pending_htlcs_forwardable!(nodes[2]);
1753
1754         let events = nodes[2].node.get_and_clear_pending_events();
1755         assert_eq!(events.len(), 2);
1756         match events[0] {
1757                 Event::PaymentReceived { ref payment_hash, amt } => {
1758                         assert_eq!(our_payment_hash_21, *payment_hash);
1759                         assert_eq!(recv_value_21, amt);
1760                 },
1761                 _ => panic!("Unexpected event"),
1762         }
1763         match events[1] {
1764                 Event::PaymentReceived { ref payment_hash, amt } => {
1765                         assert_eq!(our_payment_hash_22, *payment_hash);
1766                         assert_eq!(recv_value_22, amt);
1767                 },
1768                 _ => panic!("Unexpected event"),
1769         }
1770
1771         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1, recv_value_1);
1772         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21, recv_value_21);
1773         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22, recv_value_22);
1774
1775         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);
1776         let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
1777         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
1778         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat);
1779
1780         let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
1781         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22);
1782 }
1783
1784 #[test]
1785 fn channel_reserve_test() {
1786         do_channel_reserve_test(false);
1787         do_channel_reserve_test(true);
1788 }
1789
1790 #[test]
1791 fn channel_reserve_in_flight_removes() {
1792         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
1793         // can send to its counterparty, but due to update ordering, the other side may not yet have
1794         // considered those HTLCs fully removed.
1795         // This tests that we don't count HTLCs which will not be included in the next remote
1796         // commitment transaction towards the reserve value (as it implies no commitment transaction
1797         // will be generated which violates the remote reserve value).
1798         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
1799         // To test this we:
1800         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
1801         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
1802         //    you only consider the value of the first HTLC, it may not),
1803         //  * start routing a third HTLC from A to B,
1804         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
1805         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
1806         //  * deliver the first fulfill from B
1807         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
1808         //    claim,
1809         //  * deliver A's response CS and RAA.
1810         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
1811         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
1812         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
1813         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
1814         let chanmon_cfgs = create_chanmon_cfgs(2);
1815         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1816         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1817         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1818         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
1819
1820         let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
1821         // Route the first two HTLCs.
1822         let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
1823         let (payment_preimage_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
1824
1825         // Start routing the third HTLC (this is just used to get everyone in the right state).
1826         let (payment_preimage_3, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
1827         let send_1 = {
1828                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
1829                 nodes[0].node.send_payment(route, payment_hash_3).unwrap();
1830                 check_added_monitors!(nodes[0], 1);
1831                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1832                 assert_eq!(events.len(), 1);
1833                 SendEvent::from_event(events.remove(0))
1834         };
1835
1836         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
1837         // initial fulfill/CS.
1838         assert!(nodes[1].node.claim_funds(payment_preimage_1, b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000));
1839         check_added_monitors!(nodes[1], 1);
1840         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1841
1842         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
1843         // remove the second HTLC when we send the HTLC back from B to A.
1844         assert!(nodes[1].node.claim_funds(payment_preimage_2, 20000));
1845         check_added_monitors!(nodes[1], 1);
1846         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1847
1848         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
1849         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
1850         check_added_monitors!(nodes[0], 1);
1851         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1852         expect_payment_sent!(nodes[0], payment_preimage_1);
1853
1854         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
1855         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
1856         check_added_monitors!(nodes[1], 1);
1857         // B is already AwaitingRAA, so cant generate a CS here
1858         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1859
1860         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1861         check_added_monitors!(nodes[1], 1);
1862         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1863
1864         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1865         check_added_monitors!(nodes[0], 1);
1866         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1867
1868         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1869         check_added_monitors!(nodes[1], 1);
1870         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1871
1872         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
1873         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
1874         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
1875         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
1876         // on-chain as necessary).
1877         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
1878         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
1879         check_added_monitors!(nodes[0], 1);
1880         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1881         expect_payment_sent!(nodes[0], payment_preimage_2);
1882
1883         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1884         check_added_monitors!(nodes[1], 1);
1885         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1886
1887         expect_pending_htlcs_forwardable!(nodes[1]);
1888         expect_payment_received!(nodes[1], payment_hash_3, 100000);
1889
1890         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
1891         // resolve the second HTLC from A's point of view.
1892         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1893         check_added_monitors!(nodes[0], 1);
1894         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1895
1896         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
1897         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
1898         let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[1]);
1899         let send_2 = {
1900                 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &[], 10000, TEST_FINAL_CLTV).unwrap();
1901                 nodes[1].node.send_payment(route, payment_hash_4).unwrap();
1902                 check_added_monitors!(nodes[1], 1);
1903                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1904                 assert_eq!(events.len(), 1);
1905                 SendEvent::from_event(events.remove(0))
1906         };
1907
1908         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
1909         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
1910         check_added_monitors!(nodes[0], 1);
1911         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1912
1913         // Now just resolve all the outstanding messages/HTLCs for completeness...
1914
1915         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1916         check_added_monitors!(nodes[1], 1);
1917         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1918
1919         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1920         check_added_monitors!(nodes[1], 1);
1921
1922         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1923         check_added_monitors!(nodes[0], 1);
1924         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1925
1926         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1927         check_added_monitors!(nodes[1], 1);
1928         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1929
1930         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1931         check_added_monitors!(nodes[0], 1);
1932
1933         expect_pending_htlcs_forwardable!(nodes[0]);
1934         expect_payment_received!(nodes[0], payment_hash_4, 10000);
1935
1936         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4, 10_000);
1937         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3, 100_000);
1938 }
1939
1940 #[test]
1941 fn channel_monitor_network_test() {
1942         // Simple test which builds a network of ChannelManagers, connects them to each other, and
1943         // tests that ChannelMonitor is able to recover from various states.
1944         let chanmon_cfgs = create_chanmon_cfgs(5);
1945         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
1946         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
1947         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
1948
1949         // Create some initial channels
1950         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
1951         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
1952         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::supported(), InitFeatures::supported());
1953         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::supported(), InitFeatures::supported());
1954
1955         // Rebalance the network a bit by relaying one payment through all the channels...
1956         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
1957         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
1958         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
1959         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
1960
1961         // Simple case with no pending HTLCs:
1962         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
1963         check_added_monitors!(nodes[1], 1);
1964         {
1965                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
1966                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1967                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
1968                 check_added_monitors!(nodes[0], 1);
1969                 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
1970         }
1971         get_announce_close_broadcast_events(&nodes, 0, 1);
1972         assert_eq!(nodes[0].node.list_channels().len(), 0);
1973         assert_eq!(nodes[1].node.list_channels().len(), 1);
1974
1975         // One pending HTLC is discarded by the force-close:
1976         let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
1977
1978         // Simple case of one pending HTLC to HTLC-Timeout
1979         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
1980         check_added_monitors!(nodes[1], 1);
1981         {
1982                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
1983                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1984                 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
1985                 check_added_monitors!(nodes[2], 1);
1986                 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
1987         }
1988         get_announce_close_broadcast_events(&nodes, 1, 2);
1989         assert_eq!(nodes[1].node.list_channels().len(), 0);
1990         assert_eq!(nodes[2].node.list_channels().len(), 1);
1991
1992         macro_rules! claim_funds {
1993                 ($node: expr, $prev_node: expr, $preimage: expr, $amount: expr) => {
1994                         {
1995                                 assert!($node.node.claim_funds($preimage, $amount));
1996                                 check_added_monitors!($node, 1);
1997
1998                                 let events = $node.node.get_and_clear_pending_msg_events();
1999                                 assert_eq!(events.len(), 1);
2000                                 match events[0] {
2001                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2002                                                 assert!(update_add_htlcs.is_empty());
2003                                                 assert!(update_fail_htlcs.is_empty());
2004                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2005                                         },
2006                                         _ => panic!("Unexpected event"),
2007                                 };
2008                         }
2009                 }
2010         }
2011
2012         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2013         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2014         nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2015         check_added_monitors!(nodes[2], 1);
2016         let node2_commitment_txid;
2017         {
2018                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2019                 node2_commitment_txid = node_txn[0].txid();
2020
2021                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2022                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, 3_000_000);
2023
2024                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2025                 nodes[3].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
2026                 check_added_monitors!(nodes[3], 1);
2027
2028                 check_preimage_claim(&nodes[3], &node_txn);
2029         }
2030         get_announce_close_broadcast_events(&nodes, 2, 3);
2031         assert_eq!(nodes[2].node.list_channels().len(), 0);
2032         assert_eq!(nodes[3].node.list_channels().len(), 1);
2033
2034         { // Cheat and reset nodes[4]'s height to 1
2035                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2036                 nodes[4].block_notifier.block_connected(&Block { header, txdata: vec![] }, 1);
2037         }
2038
2039         assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
2040         assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
2041         // One pending HTLC to time out:
2042         let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2043         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2044         // buffer space).
2045
2046         {
2047                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2048                 nodes[3].block_notifier.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
2049                 for i in 3..TEST_FINAL_CLTV + 2 + LATENCY_GRACE_PERIOD_BLOCKS + 1 {
2050                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2051                         nodes[3].block_notifier.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
2052                 }
2053                 check_added_monitors!(nodes[3], 1);
2054
2055                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2056                 {
2057                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2058                         node_txn.retain(|tx| {
2059                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2060                                         false
2061                                 } else { true }
2062                         });
2063                 }
2064
2065                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2066
2067                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2068                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, 3_000_000);
2069
2070                 header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2071
2072                 nodes[4].block_notifier.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
2073                 for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
2074                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2075                         nodes[4].block_notifier.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
2076                 }
2077
2078                 check_added_monitors!(nodes[4], 1);
2079                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2080
2081                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2082                 nodes[4].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, TEST_FINAL_CLTV - 5);
2083
2084                 check_preimage_claim(&nodes[4], &node_txn);
2085         }
2086         get_announce_close_broadcast_events(&nodes, 3, 4);
2087         assert_eq!(nodes[3].node.list_channels().len(), 0);
2088         assert_eq!(nodes[4].node.list_channels().len(), 0);
2089 }
2090
2091 #[test]
2092 fn test_justice_tx() {
2093         // Test justice txn built on revoked HTLC-Success tx, against both sides
2094         let mut alice_config = UserConfig::default();
2095         alice_config.channel_options.announced_channel = true;
2096         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2097         alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2098         let mut bob_config = UserConfig::default();
2099         bob_config.channel_options.announced_channel = true;
2100         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2101         bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2102         let user_cfgs = [Some(alice_config), Some(bob_config)];
2103         let chanmon_cfgs = create_chanmon_cfgs(2);
2104         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2105         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2106         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2107         // Create some new channels:
2108         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
2109
2110         // A pending HTLC which will be revoked:
2111         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2112         // Get the will-be-revoked local txn from nodes[0]
2113         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2114         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2115         assert_eq!(revoked_local_txn[0].input.len(), 1);
2116         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2117         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2118         assert_eq!(revoked_local_txn[1].input.len(), 1);
2119         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2120         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2121         // Revoke the old state
2122         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 3_000_000);
2123
2124         {
2125                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2126                 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2127                 {
2128                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2129                         assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2130                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2131
2132                         check_spends!(node_txn[0], revoked_local_txn[0]);
2133                         node_txn.swap_remove(0);
2134                         node_txn.truncate(1);
2135                 }
2136                 check_added_monitors!(nodes[1], 1);
2137                 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2138
2139                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2140                 // Verify broadcast of revoked HTLC-timeout
2141                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2142                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2143                 check_added_monitors!(nodes[0], 1);
2144                 // Broadcast revoked HTLC-timeout on node 1
2145                 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2146                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2147         }
2148         get_announce_close_broadcast_events(&nodes, 0, 1);
2149
2150         assert_eq!(nodes[0].node.list_channels().len(), 0);
2151         assert_eq!(nodes[1].node.list_channels().len(), 0);
2152
2153         // We test justice_tx build by A on B's revoked HTLC-Success tx
2154         // Create some new channels:
2155         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
2156         {
2157                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2158                 node_txn.clear();
2159         }
2160
2161         // A pending HTLC which will be revoked:
2162         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2163         // Get the will-be-revoked local txn from B
2164         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2165         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2166         assert_eq!(revoked_local_txn[0].input.len(), 1);
2167         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2168         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2169         // Revoke the old state
2170         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4, 3_000_000);
2171         {
2172                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2173                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2174                 {
2175                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2176                         assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2177                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2178
2179                         check_spends!(node_txn[0], revoked_local_txn[0]);
2180                         node_txn.swap_remove(0);
2181                 }
2182                 check_added_monitors!(nodes[0], 1);
2183                 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2184
2185                 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2186                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2187                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2188                 check_added_monitors!(nodes[1], 1);
2189                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2190                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2191         }
2192         get_announce_close_broadcast_events(&nodes, 0, 1);
2193         assert_eq!(nodes[0].node.list_channels().len(), 0);
2194         assert_eq!(nodes[1].node.list_channels().len(), 0);
2195 }
2196
2197 #[test]
2198 fn revoked_output_claim() {
2199         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2200         // transaction is broadcast by its counterparty
2201         let chanmon_cfgs = create_chanmon_cfgs(2);
2202         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2203         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2204         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2205         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
2206         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2207         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2208         assert_eq!(revoked_local_txn.len(), 1);
2209         // Only output is the full channel value back to nodes[0]:
2210         assert_eq!(revoked_local_txn[0].output.len(), 1);
2211         // Send a payment through, updating everyone's latest commitment txn
2212         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000, 5_000_000);
2213
2214         // Inform nodes[1] that nodes[0] broadcast a stale tx
2215         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2216         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2217         check_added_monitors!(nodes[1], 1);
2218         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2219         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2220
2221         check_spends!(node_txn[0], revoked_local_txn[0]);
2222         check_spends!(node_txn[1], chan_1.3);
2223
2224         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2225         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2226         get_announce_close_broadcast_events(&nodes, 0, 1);
2227         check_added_monitors!(nodes[0], 1)
2228 }
2229
2230 #[test]
2231 fn claim_htlc_outputs_shared_tx() {
2232         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2233         let chanmon_cfgs = create_chanmon_cfgs(2);
2234         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2235         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2236         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2237
2238         // Create some new channel:
2239         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
2240
2241         // Rebalance the network to generate htlc in the two directions
2242         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2243         // 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
2244         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2245         let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2246
2247         // Get the will-be-revoked local txn from node[0]
2248         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2249         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2250         assert_eq!(revoked_local_txn[0].input.len(), 1);
2251         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2252         assert_eq!(revoked_local_txn[1].input.len(), 1);
2253         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2254         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2255         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2256
2257         //Revoke the old state
2258         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2259
2260         {
2261                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2262                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2263                 check_added_monitors!(nodes[0], 1);
2264                 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2265                 check_added_monitors!(nodes[1], 1);
2266                 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2267
2268                 let events = nodes[1].node.get_and_clear_pending_events();
2269                 assert_eq!(events.len(), 1);
2270                 match events[0] {
2271                         Event::PaymentFailed { payment_hash, .. } => {
2272                                 assert_eq!(payment_hash, payment_hash_2);
2273                         },
2274                         _ => panic!("Unexpected event"),
2275                 }
2276
2277                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2278                 assert_eq!(node_txn.len(), 3); // ChannelMonitor: penalty tx, ChannelManager: local commitment + HTLC-timeout
2279
2280                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2281                 check_spends!(node_txn[0], revoked_local_txn[0]);
2282
2283                 let mut witness_lens = BTreeSet::new();
2284                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2285                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2286                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2287                 assert_eq!(witness_lens.len(), 3);
2288                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2289                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2290                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2291
2292                 // Next nodes[1] broadcasts its current local tx state:
2293                 assert_eq!(node_txn[1].input.len(), 1);
2294                 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2295
2296                 assert_eq!(node_txn[2].input.len(), 1);
2297                 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
2298                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2299                 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
2300                 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
2301                 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
2302         }
2303         get_announce_close_broadcast_events(&nodes, 0, 1);
2304         assert_eq!(nodes[0].node.list_channels().len(), 0);
2305         assert_eq!(nodes[1].node.list_channels().len(), 0);
2306 }
2307
2308 #[test]
2309 fn claim_htlc_outputs_single_tx() {
2310         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2311         let chanmon_cfgs = create_chanmon_cfgs(2);
2312         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2313         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2314         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2315
2316         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
2317
2318         // Rebalance the network to generate htlc in the two directions
2319         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2320         // 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
2321         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2322         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2323         let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2324
2325         // Get the will-be-revoked local txn from node[0]
2326         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2327
2328         //Revoke the old state
2329         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2330
2331         {
2332                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2333                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2334                 check_added_monitors!(nodes[0], 1);
2335                 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2336                 check_added_monitors!(nodes[1], 1);
2337                 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 200, true, header.bitcoin_hash());
2338
2339                 let events = nodes[1].node.get_and_clear_pending_events();
2340                 assert_eq!(events.len(), 1);
2341                 match events[0] {
2342                         Event::PaymentFailed { payment_hash, .. } => {
2343                                 assert_eq!(payment_hash, payment_hash_2);
2344                         },
2345                         _ => panic!("Unexpected event"),
2346                 }
2347
2348                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2349                 assert_eq!(node_txn.len(), 21);
2350                 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2351                 // ChannelManager: local commmitment + local HTLC-timeout (2)
2352                 // ChannelMonitor: bumped justice tx (4), after one increase, bumps on HTLC aren't generated not being substantial anymore
2353                 // ChannelMonito r: local commitment + local HTLC-timeout (14)
2354
2355                 assert_eq!(node_txn[0], node_txn[5]);
2356                 assert_eq!(node_txn[0], node_txn[7]);
2357                 assert_eq!(node_txn[0], node_txn[9]);
2358                 assert_eq!(node_txn[0], node_txn[13]);
2359                 assert_eq!(node_txn[0], node_txn[15]);
2360                 assert_eq!(node_txn[0], node_txn[17]);
2361                 assert_eq!(node_txn[0], node_txn[19]);
2362
2363                 assert_eq!(node_txn[1], node_txn[6]);
2364                 assert_eq!(node_txn[1], node_txn[8]);
2365                 assert_eq!(node_txn[1], node_txn[10]);
2366                 assert_eq!(node_txn[1], node_txn[14]);
2367                 assert_eq!(node_txn[1], node_txn[16]);
2368                 assert_eq!(node_txn[1], node_txn[18]);
2369                 assert_eq!(node_txn[1], node_txn[20]);
2370
2371
2372                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration and present 8 times (rebroadcast at every block from 200 to 206)
2373                 assert_eq!(node_txn[0].input.len(), 1);
2374                 check_spends!(node_txn[0], chan_1.3);
2375                 assert_eq!(node_txn[1].input.len(), 1);
2376                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2377                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2378                 check_spends!(node_txn[1], node_txn[0]);
2379
2380                 // Justice transactions are indices 2-3-4
2381                 assert_eq!(node_txn[2].input.len(), 1);
2382                 assert_eq!(node_txn[3].input.len(), 1);
2383                 assert_eq!(node_txn[4].input.len(), 1);
2384                 check_spends!(node_txn[2], revoked_local_txn[0]);
2385                 check_spends!(node_txn[3], revoked_local_txn[0]);
2386                 check_spends!(node_txn[4], revoked_local_txn[0]);
2387
2388                 let mut witness_lens = BTreeSet::new();
2389                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2390                 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2391                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2392                 assert_eq!(witness_lens.len(), 3);
2393                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2394                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2395                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2396         }
2397         get_announce_close_broadcast_events(&nodes, 0, 1);
2398         assert_eq!(nodes[0].node.list_channels().len(), 0);
2399         assert_eq!(nodes[1].node.list_channels().len(), 0);
2400 }
2401
2402 #[test]
2403 fn test_htlc_on_chain_success() {
2404         // Test that in case of a unilateral close onchain, we detect the state of output thanks to
2405         // ChainWatchInterface and pass the preimage backward accordingly. So here we test that ChannelManager is
2406         // broadcasting the right event to other nodes in payment path.
2407         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2408         // A --------------------> B ----------------------> C (preimage)
2409         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2410         // commitment transaction was broadcast.
2411         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2412         // towards B.
2413         // B should be able to claim via preimage if A then broadcasts its local tx.
2414         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2415         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2416         // PaymentSent event).
2417
2418         let chanmon_cfgs = create_chanmon_cfgs(3);
2419         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2420         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2421         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2422
2423         // Create some initial channels
2424         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
2425         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
2426
2427         // Rebalance the network a bit by relaying one payment through all the channels...
2428         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2429         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2430
2431         let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2432         let (our_payment_preimage_2, _payment_hash_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2433         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2434
2435         // Broadcast legit commitment tx from C on B's chain
2436         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2437         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2438         assert_eq!(commitment_tx.len(), 1);
2439         check_spends!(commitment_tx[0], chan_2.3);
2440         nodes[2].node.claim_funds(our_payment_preimage, 3_000_000);
2441         nodes[2].node.claim_funds(our_payment_preimage_2, 3_000_000);
2442         check_added_monitors!(nodes[2], 2);
2443         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2444         assert!(updates.update_add_htlcs.is_empty());
2445         assert!(updates.update_fail_htlcs.is_empty());
2446         assert!(updates.update_fail_malformed_htlcs.is_empty());
2447         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2448
2449         nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2450         check_closed_broadcast!(nodes[2], false);
2451         check_added_monitors!(nodes[2], 1);
2452         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx, 2*htlc-success tx), ChannelMonitor : 4 (2*2 * HTLC-Success tx)
2453         assert_eq!(node_txn.len(), 7);
2454         assert_eq!(node_txn[0], node_txn[3]);
2455         assert_eq!(node_txn[1], node_txn[4]);
2456         assert_eq!(node_txn[0], node_txn[5]);
2457         assert_eq!(node_txn[1], node_txn[6]);
2458         assert_eq!(node_txn[2], commitment_tx[0]);
2459         check_spends!(node_txn[0], commitment_tx[0]);
2460         check_spends!(node_txn[1], commitment_tx[0]);
2461         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2462         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2463         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2464         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2465         assert_eq!(node_txn[0].lock_time, 0);
2466         assert_eq!(node_txn[1].lock_time, 0);
2467
2468         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2469         nodes[1].block_notifier.block_connected(&Block { header, txdata: node_txn}, 1);
2470         {
2471                 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
2472                 assert_eq!(added_monitors.len(), 1);
2473                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2474                 added_monitors.clear();
2475         }
2476         let events = nodes[1].node.get_and_clear_pending_msg_events();
2477         {
2478                 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
2479                 assert_eq!(added_monitors.len(), 2);
2480                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2481                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2482                 added_monitors.clear();
2483         }
2484         assert_eq!(events.len(), 2);
2485         match events[0] {
2486                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2487                 _ => panic!("Unexpected event"),
2488         }
2489         match events[1] {
2490                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
2491                         assert!(update_add_htlcs.is_empty());
2492                         assert!(update_fail_htlcs.is_empty());
2493                         assert_eq!(update_fulfill_htlcs.len(), 1);
2494                         assert!(update_fail_malformed_htlcs.is_empty());
2495                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2496                 },
2497                 _ => panic!("Unexpected event"),
2498         };
2499         macro_rules! check_tx_local_broadcast {
2500                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2501                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2502                         assert_eq!(node_txn.len(), if $htlc_offered { 7 } else { 5 });
2503                         // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2504                         // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout * 2 (block-rescan)
2505                         check_spends!(node_txn[0], $commitment_tx);
2506                         check_spends!(node_txn[1], $commitment_tx);
2507                         if $htlc_offered {
2508                                 assert_eq!(node_txn[0], node_txn[5]);
2509                                 assert_eq!(node_txn[1], node_txn[6]);
2510                         }
2511                         assert_ne!(node_txn[0].lock_time, 0);
2512                         assert_ne!(node_txn[1].lock_time, 0);
2513                         if $htlc_offered {
2514                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2515                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2516                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2517                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2518                         } else {
2519                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2520                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2521                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2522                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2523                         }
2524                         check_spends!(node_txn[2], $chan_tx);
2525                         check_spends!(node_txn[3], node_txn[2]);
2526                         check_spends!(node_txn[4], node_txn[2]);
2527                         assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), 71);
2528                         assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2529                         assert_eq!(node_txn[4].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2530                         assert!(node_txn[3].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2531                         assert!(node_txn[4].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2532                         assert_ne!(node_txn[3].lock_time, 0);
2533                         assert_ne!(node_txn[4].lock_time, 0);
2534                         node_txn.clear();
2535                 } }
2536         }
2537         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2538         // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2539         // timeout-claim of the output that nodes[2] just claimed via success.
2540         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2541
2542         // Broadcast legit commitment tx from A on B's chain
2543         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2544         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2545         check_spends!(commitment_tx[0], chan_1.3);
2546         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2547         check_closed_broadcast!(nodes[1], false);
2548         check_added_monitors!(nodes[1], 1);
2549         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 1 (HTLC-Success)
2550         assert_eq!(node_txn.len(), 4);
2551         check_spends!(node_txn[0], commitment_tx[0]);
2552         assert_eq!(node_txn[0].input.len(), 2);
2553         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2554         assert_eq!(node_txn[0].input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2555         assert_eq!(node_txn[0].lock_time, 0);
2556         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2557         check_spends!(node_txn[1], chan_1.3);
2558         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
2559         check_spends!(node_txn[2], node_txn[1]);
2560         check_spends!(node_txn[3], node_txn[1]);
2561         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2562         // we already checked the same situation with A.
2563
2564         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2565         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
2566         check_closed_broadcast!(nodes[0], false);
2567         check_added_monitors!(nodes[0], 1);
2568         let events = nodes[0].node.get_and_clear_pending_events();
2569         assert_eq!(events.len(), 2);
2570         let mut first_claimed = false;
2571         for event in events {
2572                 match event {
2573                         Event::PaymentSent { payment_preimage } => {
2574                                 if payment_preimage == our_payment_preimage {
2575                                         assert!(!first_claimed);
2576                                         first_claimed = true;
2577                                 } else {
2578                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2579                                 }
2580                         },
2581                         _ => panic!("Unexpected event"),
2582                 }
2583         }
2584         check_tx_local_broadcast!(nodes[0], true, commitment_tx[0], chan_1.3);
2585 }
2586
2587 #[test]
2588 fn test_htlc_on_chain_timeout() {
2589         // Test that in case of a unilateral close onchain, we detect the state of output thanks to
2590         // ChainWatchInterface and timeout the HTLC backward accordingly. So here we test that ChannelManager is
2591         // broadcasting the right event to other nodes in payment path.
2592         // A ------------------> B ----------------------> C (timeout)
2593         //    B's commitment tx                 C's commitment tx
2594         //            \                                  \
2595         //         B's HTLC timeout tx               B's timeout tx
2596
2597         let chanmon_cfgs = create_chanmon_cfgs(3);
2598         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2599         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2600         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2601
2602         // Create some intial channels
2603         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
2604         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
2605
2606         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2607         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2608         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2609
2610         let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2611         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2612
2613         // Broadcast legit commitment tx from C on B's chain
2614         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2615         check_spends!(commitment_tx[0], chan_2.3);
2616         nodes[2].node.fail_htlc_backwards(&payment_hash);
2617         check_added_monitors!(nodes[2], 0);
2618         expect_pending_htlcs_forwardable!(nodes[2]);
2619         check_added_monitors!(nodes[2], 1);
2620
2621         let events = nodes[2].node.get_and_clear_pending_msg_events();
2622         assert_eq!(events.len(), 1);
2623         match events[0] {
2624                 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, .. } } => {
2625                         assert!(update_add_htlcs.is_empty());
2626                         assert!(!update_fail_htlcs.is_empty());
2627                         assert!(update_fulfill_htlcs.is_empty());
2628                         assert!(update_fail_malformed_htlcs.is_empty());
2629                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2630                 },
2631                 _ => panic!("Unexpected event"),
2632         };
2633         nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2634         check_closed_broadcast!(nodes[2], false);
2635         check_added_monitors!(nodes[2], 1);
2636         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2637         assert_eq!(node_txn.len(), 1);
2638         check_spends!(node_txn[0], chan_2.3);
2639         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2640
2641         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2642         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2643         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
2644         let timeout_tx;
2645         {
2646                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2647                 assert_eq!(node_txn.len(), 7); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : (local commitment tx + HTLC-timeout) * 2 (block-rescan), timeout tx
2648                 assert_eq!(node_txn[0], node_txn[3]);
2649                 assert_eq!(node_txn[0], node_txn[5]);
2650                 assert_eq!(node_txn[1], node_txn[4]);
2651                 assert_eq!(node_txn[1], node_txn[6]);
2652
2653                 check_spends!(node_txn[2], commitment_tx[0]);
2654                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2655
2656                 check_spends!(node_txn[0], chan_2.3);
2657                 check_spends!(node_txn[1], node_txn[0]);
2658                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2659                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2660
2661                 timeout_tx = node_txn[2].clone();
2662                 node_txn.clear();
2663         }
2664
2665         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![timeout_tx]}, 1);
2666         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2667         check_added_monitors!(nodes[1], 1);
2668         check_closed_broadcast!(nodes[1], false);
2669
2670         expect_pending_htlcs_forwardable!(nodes[1]);
2671         check_added_monitors!(nodes[1], 1);
2672         let events = nodes[1].node.get_and_clear_pending_msg_events();
2673         assert_eq!(events.len(), 1);
2674         match events[0] {
2675                 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, .. } } => {
2676                         assert!(update_add_htlcs.is_empty());
2677                         assert!(!update_fail_htlcs.is_empty());
2678                         assert!(update_fulfill_htlcs.is_empty());
2679                         assert!(update_fail_malformed_htlcs.is_empty());
2680                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2681                 },
2682                 _ => panic!("Unexpected event"),
2683         };
2684         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
2685         assert_eq!(node_txn.len(), 0);
2686
2687         // Broadcast legit commitment tx from B on A's chain
2688         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2689         check_spends!(commitment_tx[0], chan_1.3);
2690
2691         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
2692         check_closed_broadcast!(nodes[0], false);
2693         check_added_monitors!(nodes[0], 1);
2694         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 1 timeout tx
2695         assert_eq!(node_txn.len(), 3);
2696         check_spends!(node_txn[0], commitment_tx[0]);
2697         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2698         check_spends!(node_txn[1], chan_1.3);
2699         check_spends!(node_txn[2], node_txn[1]);
2700         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
2701         assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2702 }
2703
2704 #[test]
2705 fn test_simple_commitment_revoked_fail_backward() {
2706         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
2707         // and fail backward accordingly.
2708
2709         let chanmon_cfgs = create_chanmon_cfgs(3);
2710         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2711         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2712         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2713
2714         // Create some initial channels
2715         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
2716         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
2717
2718         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2719         // Get the will-be-revoked local txn from nodes[2]
2720         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2721         // Revoke the old state
2722         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, 3_000_000);
2723
2724         route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2725
2726         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2727         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2728         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2729         check_added_monitors!(nodes[1], 1);
2730         check_closed_broadcast!(nodes[1], false);
2731
2732         expect_pending_htlcs_forwardable!(nodes[1]);
2733         check_added_monitors!(nodes[1], 1);
2734         let events = nodes[1].node.get_and_clear_pending_msg_events();
2735         assert_eq!(events.len(), 1);
2736         match events[0] {
2737                 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, .. } } => {
2738                         assert!(update_add_htlcs.is_empty());
2739                         assert_eq!(update_fail_htlcs.len(), 1);
2740                         assert!(update_fulfill_htlcs.is_empty());
2741                         assert!(update_fail_malformed_htlcs.is_empty());
2742                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2743
2744                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
2745                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2746
2747                         let events = nodes[0].node.get_and_clear_pending_msg_events();
2748                         assert_eq!(events.len(), 1);
2749                         match events[0] {
2750                                 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
2751                                 _ => panic!("Unexpected event"),
2752                         }
2753                         let events = nodes[0].node.get_and_clear_pending_events();
2754                         assert_eq!(events.len(), 1);
2755                         match events[0] {
2756                                 Event::PaymentFailed { .. } => {},
2757                                 _ => panic!("Unexpected event"),
2758                         }
2759                 },
2760                 _ => panic!("Unexpected event"),
2761         }
2762 }
2763
2764 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
2765         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
2766         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
2767         // commitment transaction anymore.
2768         // To do this, we have the peer which will broadcast a revoked commitment transaction send
2769         // a number of update_fail/commitment_signed updates without ever sending the RAA in
2770         // response to our commitment_signed. This is somewhat misbehavior-y, though not
2771         // technically disallowed and we should probably handle it reasonably.
2772         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
2773         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
2774         // transactions:
2775         // * Once we move it out of our holding cell/add it, we will immediately include it in a
2776         //   commitment_signed (implying it will be in the latest remote commitment transaction).
2777         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
2778         //   and once they revoke the previous commitment transaction (allowing us to send a new
2779         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
2780         let chanmon_cfgs = create_chanmon_cfgs(3);
2781         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2782         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2783         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2784
2785         // Create some initial channels
2786         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
2787         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
2788
2789         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
2790         // Get the will-be-revoked local txn from nodes[2]
2791         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2792         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
2793         // Revoke the old state
2794         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, if no_to_remote { 10_000 } else { 3_000_000});
2795
2796         let value = if use_dust {
2797                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
2798                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
2799                 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().our_dust_limit_satoshis * 1000
2800         } else { 3000000 };
2801
2802         let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2803         let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2804         let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2805
2806         assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash));
2807         expect_pending_htlcs_forwardable!(nodes[2]);
2808         check_added_monitors!(nodes[2], 1);
2809         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2810         assert!(updates.update_add_htlcs.is_empty());
2811         assert!(updates.update_fulfill_htlcs.is_empty());
2812         assert!(updates.update_fail_malformed_htlcs.is_empty());
2813         assert_eq!(updates.update_fail_htlcs.len(), 1);
2814         assert!(updates.update_fee.is_none());
2815         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2816         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
2817         // Drop the last RAA from 3 -> 2
2818
2819         assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash));
2820         expect_pending_htlcs_forwardable!(nodes[2]);
2821         check_added_monitors!(nodes[2], 1);
2822         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2823         assert!(updates.update_add_htlcs.is_empty());
2824         assert!(updates.update_fulfill_htlcs.is_empty());
2825         assert!(updates.update_fail_malformed_htlcs.is_empty());
2826         assert_eq!(updates.update_fail_htlcs.len(), 1);
2827         assert!(updates.update_fee.is_none());
2828         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2829         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
2830         check_added_monitors!(nodes[1], 1);
2831         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
2832         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2833         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
2834         check_added_monitors!(nodes[2], 1);
2835
2836         assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash));
2837         expect_pending_htlcs_forwardable!(nodes[2]);
2838         check_added_monitors!(nodes[2], 1);
2839         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2840         assert!(updates.update_add_htlcs.is_empty());
2841         assert!(updates.update_fulfill_htlcs.is_empty());
2842         assert!(updates.update_fail_malformed_htlcs.is_empty());
2843         assert_eq!(updates.update_fail_htlcs.len(), 1);
2844         assert!(updates.update_fee.is_none());
2845         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2846         // At this point first_payment_hash has dropped out of the latest two commitment
2847         // transactions that nodes[1] is tracking...
2848         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
2849         check_added_monitors!(nodes[1], 1);
2850         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
2851         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2852         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
2853         check_added_monitors!(nodes[2], 1);
2854
2855         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
2856         // on nodes[2]'s RAA.
2857         let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
2858         let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
2859         nodes[1].node.send_payment(route, fourth_payment_hash).unwrap();
2860         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2861         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2862         check_added_monitors!(nodes[1], 0);
2863
2864         if deliver_bs_raa {
2865                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
2866                 // One monitor for the new revocation preimage, no second on as we won't generate a new
2867                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
2868                 check_added_monitors!(nodes[1], 1);
2869                 let events = nodes[1].node.get_and_clear_pending_events();
2870                 assert_eq!(events.len(), 1);
2871                 match events[0] {
2872                         Event::PendingHTLCsForwardable { .. } => { },
2873                         _ => panic!("Unexpected event"),
2874                 };
2875                 // Deliberately don't process the pending fail-back so they all fail back at once after
2876                 // block connection just like the !deliver_bs_raa case
2877         }
2878
2879         let mut failed_htlcs = HashSet::new();
2880         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2881
2882         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2883         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2884         check_added_monitors!(nodes[1], 1);
2885         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2886
2887         let events = nodes[1].node.get_and_clear_pending_events();
2888         assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
2889         match events[0] {
2890                 Event::PaymentFailed { ref payment_hash, .. } => {
2891                         assert_eq!(*payment_hash, fourth_payment_hash);
2892                 },
2893                 _ => panic!("Unexpected event"),
2894         }
2895         if !deliver_bs_raa {
2896                 match events[1] {
2897                         Event::PendingHTLCsForwardable { .. } => { },
2898                         _ => panic!("Unexpected event"),
2899                 };
2900         }
2901         nodes[1].node.process_pending_htlc_forwards();
2902         check_added_monitors!(nodes[1], 1);
2903
2904         let events = nodes[1].node.get_and_clear_pending_msg_events();
2905         assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
2906         match events[if deliver_bs_raa { 1 } else { 0 }] {
2907                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
2908                 _ => panic!("Unexpected event"),
2909         }
2910         if deliver_bs_raa {
2911                 match events[0] {
2912                         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, .. } } => {
2913                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
2914                                 assert_eq!(update_add_htlcs.len(), 1);
2915                                 assert!(update_fulfill_htlcs.is_empty());
2916                                 assert!(update_fail_htlcs.is_empty());
2917                                 assert!(update_fail_malformed_htlcs.is_empty());
2918                         },
2919                         _ => panic!("Unexpected event"),
2920                 }
2921         }
2922         match events[if deliver_bs_raa { 2 } else { 1 }] {
2923                 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, .. } } => {
2924                         assert!(update_add_htlcs.is_empty());
2925                         assert_eq!(update_fail_htlcs.len(), 3);
2926                         assert!(update_fulfill_htlcs.is_empty());
2927                         assert!(update_fail_malformed_htlcs.is_empty());
2928                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2929
2930                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
2931                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
2932                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
2933
2934                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2935
2936                         let events = nodes[0].node.get_and_clear_pending_msg_events();
2937                         // If we delivered B's RAA we got an unknown preimage error, not something
2938                         // that we should update our routing table for.
2939                         assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
2940                         for event in events {
2941                                 match event {
2942                                         MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
2943                                         _ => panic!("Unexpected event"),
2944                                 }
2945                         }
2946                         let events = nodes[0].node.get_and_clear_pending_events();
2947                         assert_eq!(events.len(), 3);
2948                         match events[0] {
2949                                 Event::PaymentFailed { ref payment_hash, .. } => {
2950                                         assert!(failed_htlcs.insert(payment_hash.0));
2951                                 },
2952                                 _ => panic!("Unexpected event"),
2953                         }
2954                         match events[1] {
2955                                 Event::PaymentFailed { ref payment_hash, .. } => {
2956                                         assert!(failed_htlcs.insert(payment_hash.0));
2957                                 },
2958                                 _ => panic!("Unexpected event"),
2959                         }
2960                         match events[2] {
2961                                 Event::PaymentFailed { ref payment_hash, .. } => {
2962                                         assert!(failed_htlcs.insert(payment_hash.0));
2963                                 },
2964                                 _ => panic!("Unexpected event"),
2965                         }
2966                 },
2967                 _ => panic!("Unexpected event"),
2968         }
2969
2970         assert!(failed_htlcs.contains(&first_payment_hash.0));
2971         assert!(failed_htlcs.contains(&second_payment_hash.0));
2972         assert!(failed_htlcs.contains(&third_payment_hash.0));
2973 }
2974
2975 #[test]
2976 fn test_commitment_revoked_fail_backward_exhaustive_a() {
2977         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
2978         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
2979         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
2980         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
2981 }
2982
2983 #[test]
2984 fn test_commitment_revoked_fail_backward_exhaustive_b() {
2985         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
2986         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
2987         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
2988         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
2989 }
2990
2991 #[test]
2992 fn test_htlc_ignore_latest_remote_commitment() {
2993         // Test that HTLC transactions spending the latest remote commitment transaction are simply
2994         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
2995         let chanmon_cfgs = create_chanmon_cfgs(2);
2996         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2997         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2998         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2999         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
3000
3001         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3002         nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
3003         check_closed_broadcast!(nodes[0], false);
3004         check_added_monitors!(nodes[0], 1);
3005
3006         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3007         assert_eq!(node_txn.len(), 2);
3008
3009         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3010         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3011         check_closed_broadcast!(nodes[1], false);
3012         check_added_monitors!(nodes[1], 1);
3013
3014         // Duplicate the block_connected call since this may happen due to other listeners
3015         // registering new transactions
3016         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3017 }
3018
3019 #[test]
3020 fn test_force_close_fail_back() {
3021         // Check which HTLCs are failed-backwards on channel force-closure
3022         let chanmon_cfgs = create_chanmon_cfgs(3);
3023         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3024         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3025         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3026         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
3027         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
3028
3029         let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, 42).unwrap();
3030
3031         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3032
3033         let mut payment_event = {
3034                 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
3035                 check_added_monitors!(nodes[0], 1);
3036
3037                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3038                 assert_eq!(events.len(), 1);
3039                 SendEvent::from_event(events.remove(0))
3040         };
3041
3042         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3043         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3044
3045         expect_pending_htlcs_forwardable!(nodes[1]);
3046
3047         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3048         assert_eq!(events_2.len(), 1);
3049         payment_event = SendEvent::from_event(events_2.remove(0));
3050         assert_eq!(payment_event.msgs.len(), 1);
3051
3052         check_added_monitors!(nodes[1], 1);
3053         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3054         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3055         check_added_monitors!(nodes[2], 1);
3056         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3057
3058         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3059         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3060         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3061
3062         nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
3063         check_closed_broadcast!(nodes[2], false);
3064         check_added_monitors!(nodes[2], 1);
3065         let tx = {
3066                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3067                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3068                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3069                 // back to nodes[1] upon timeout otherwise.
3070                 assert_eq!(node_txn.len(), 1);
3071                 node_txn.remove(0)
3072         };
3073
3074         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3075         nodes[1].block_notifier.block_connected_checked(&header, 1, &[&tx], &[1]);
3076
3077         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3078         check_closed_broadcast!(nodes[1], false);
3079         check_added_monitors!(nodes[1], 1);
3080
3081         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3082         {
3083                 let mut monitors = nodes[2].chan_monitor.simple_monitor.monitors.lock().unwrap();
3084                 monitors.get_mut(&OutPoint::new(Sha256dHash::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), 0)).unwrap()
3085                         .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
3086         }
3087         nodes[2].block_notifier.block_connected_checked(&header, 1, &[&tx], &[1]);
3088         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3089         assert_eq!(node_txn.len(), 1);
3090         assert_eq!(node_txn[0].input.len(), 1);
3091         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3092         assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3093         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3094
3095         check_spends!(node_txn[0], tx);
3096 }
3097
3098 #[test]
3099 fn test_unconf_chan() {
3100         // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
3101         let chanmon_cfgs = create_chanmon_cfgs(2);
3102         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3103         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3104         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3105         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
3106
3107         let channel_state = nodes[0].node.channel_state.lock().unwrap();
3108         assert_eq!(channel_state.by_id.len(), 1);
3109         assert_eq!(channel_state.short_to_id.len(), 1);
3110         mem::drop(channel_state);
3111
3112         let mut headers = Vec::new();
3113         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3114         headers.push(header.clone());
3115         for _i in 2..100 {
3116                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3117                 headers.push(header.clone());
3118         }
3119         let mut height = 99;
3120         while !headers.is_empty() {
3121                 nodes[0].node.block_disconnected(&headers.pop().unwrap(), height);
3122                 height -= 1;
3123         }
3124         check_closed_broadcast!(nodes[0], false);
3125         check_added_monitors!(nodes[0], 1);
3126         let channel_state = nodes[0].node.channel_state.lock().unwrap();
3127         assert_eq!(channel_state.by_id.len(), 0);
3128         assert_eq!(channel_state.short_to_id.len(), 0);
3129 }
3130
3131 #[test]
3132 fn test_simple_peer_disconnect() {
3133         // Test that we can reconnect when there are no lost messages
3134         let chanmon_cfgs = create_chanmon_cfgs(3);
3135         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3136         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3137         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3138         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
3139         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
3140
3141         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3142         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3143         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3144
3145         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3146         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3147         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3148         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1, 1_000_000);
3149
3150         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3151         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3152         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3153
3154         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3155         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3156         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3157         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3158
3159         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3160         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3161
3162         claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3, 1_000_000);
3163         fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
3164
3165         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3166         {
3167                 let events = nodes[0].node.get_and_clear_pending_events();
3168                 assert_eq!(events.len(), 2);
3169                 match events[0] {
3170                         Event::PaymentSent { payment_preimage } => {
3171                                 assert_eq!(payment_preimage, payment_preimage_3);
3172                         },
3173                         _ => panic!("Unexpected event"),
3174                 }
3175                 match events[1] {
3176                         Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
3177                                 assert_eq!(payment_hash, payment_hash_5);
3178                                 assert!(rejected_by_dest);
3179                         },
3180                         _ => panic!("Unexpected event"),
3181                 }
3182         }
3183
3184         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4, 1_000_000);
3185         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3186 }
3187
3188 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
3189         // Test that we can reconnect when in-flight HTLC updates get dropped
3190         let chanmon_cfgs = create_chanmon_cfgs(2);
3191         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3192         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3193         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3194         if messages_delivered == 0 {
3195                 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::supported(), InitFeatures::supported());
3196                 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3197         } else {
3198                 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
3199         }
3200
3201         let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels()), &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
3202         let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
3203
3204         let payment_event = {
3205                 nodes[0].node.send_payment(route.clone(), payment_hash_1).unwrap();
3206                 check_added_monitors!(nodes[0], 1);
3207
3208                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3209                 assert_eq!(events.len(), 1);
3210                 SendEvent::from_event(events.remove(0))
3211         };
3212         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3213
3214         if messages_delivered < 2 {
3215                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3216         } else {
3217                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3218                 if messages_delivered >= 3 {
3219                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3220                         check_added_monitors!(nodes[1], 1);
3221                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3222
3223                         if messages_delivered >= 4 {
3224                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3225                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3226                                 check_added_monitors!(nodes[0], 1);
3227
3228                                 if messages_delivered >= 5 {
3229                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3230                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3231                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3232                                         check_added_monitors!(nodes[0], 1);
3233
3234                                         if messages_delivered >= 6 {
3235                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3236                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3237                                                 check_added_monitors!(nodes[1], 1);
3238                                         }
3239                                 }
3240                         }
3241                 }
3242         }
3243
3244         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3245         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3246         if messages_delivered < 3 {
3247                 // Even if the funding_locked messages get exchanged, as long as nothing further was
3248                 // received on either side, both sides will need to resend them.
3249                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
3250         } else if messages_delivered == 3 {
3251                 // nodes[0] still wants its RAA + commitment_signed
3252                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
3253         } else if messages_delivered == 4 {
3254                 // nodes[0] still wants its commitment_signed
3255                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3256         } else if messages_delivered == 5 {
3257                 // nodes[1] still wants its final RAA
3258                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3259         } else if messages_delivered == 6 {
3260                 // Everything was delivered...
3261                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3262         }
3263
3264         let events_1 = nodes[1].node.get_and_clear_pending_events();
3265         assert_eq!(events_1.len(), 1);
3266         match events_1[0] {
3267                 Event::PendingHTLCsForwardable { .. } => { },
3268                 _ => panic!("Unexpected event"),
3269         };
3270
3271         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3272         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3273         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3274
3275         nodes[1].node.process_pending_htlc_forwards();
3276
3277         let events_2 = nodes[1].node.get_and_clear_pending_events();
3278         assert_eq!(events_2.len(), 1);
3279         match events_2[0] {
3280                 Event::PaymentReceived { ref payment_hash, amt } => {
3281                         assert_eq!(payment_hash_1, *payment_hash);
3282                         assert_eq!(amt, 1000000);
3283                 },
3284                 _ => panic!("Unexpected event"),
3285         }
3286
3287         nodes[1].node.claim_funds(payment_preimage_1, 1_000_000);
3288         check_added_monitors!(nodes[1], 1);
3289
3290         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3291         assert_eq!(events_3.len(), 1);
3292         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3293                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3294                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3295                         assert!(updates.update_add_htlcs.is_empty());
3296                         assert!(updates.update_fail_htlcs.is_empty());
3297                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3298                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3299                         assert!(updates.update_fee.is_none());
3300                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3301                 },
3302                 _ => panic!("Unexpected event"),
3303         };
3304
3305         if messages_delivered >= 1 {
3306                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3307
3308                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3309                 assert_eq!(events_4.len(), 1);
3310                 match events_4[0] {
3311                         Event::PaymentSent { ref payment_preimage } => {
3312                                 assert_eq!(payment_preimage_1, *payment_preimage);
3313                         },
3314                         _ => panic!("Unexpected event"),
3315                 }
3316
3317                 if messages_delivered >= 2 {
3318                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3319                         check_added_monitors!(nodes[0], 1);
3320                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3321
3322                         if messages_delivered >= 3 {
3323                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3324                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3325                                 check_added_monitors!(nodes[1], 1);
3326
3327                                 if messages_delivered >= 4 {
3328                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3329                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3330                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3331                                         check_added_monitors!(nodes[1], 1);
3332
3333                                         if messages_delivered >= 5 {
3334                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3335                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3336                                                 check_added_monitors!(nodes[0], 1);
3337                                         }
3338                                 }
3339                         }
3340                 }
3341         }
3342
3343         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3344         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3345         if messages_delivered < 2 {
3346                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
3347                 //TODO: Deduplicate PaymentSent events, then enable this if:
3348                 //if messages_delivered < 1 {
3349                         let events_4 = nodes[0].node.get_and_clear_pending_events();
3350                         assert_eq!(events_4.len(), 1);
3351                         match events_4[0] {
3352                                 Event::PaymentSent { ref payment_preimage } => {
3353                                         assert_eq!(payment_preimage_1, *payment_preimage);
3354                                 },
3355                                 _ => panic!("Unexpected event"),
3356                         }
3357                 //}
3358         } else if messages_delivered == 2 {
3359                 // nodes[0] still wants its RAA + commitment_signed
3360                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
3361         } else if messages_delivered == 3 {
3362                 // nodes[0] still wants its commitment_signed
3363                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
3364         } else if messages_delivered == 4 {
3365                 // nodes[1] still wants its final RAA
3366                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3367         } else if messages_delivered == 5 {
3368                 // Everything was delivered...
3369                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3370         }
3371
3372         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3373         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3374         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3375
3376         // Channel should still work fine...
3377         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3378         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3379 }
3380
3381 #[test]
3382 fn test_drop_messages_peer_disconnect_a() {
3383         do_test_drop_messages_peer_disconnect(0);
3384         do_test_drop_messages_peer_disconnect(1);
3385         do_test_drop_messages_peer_disconnect(2);
3386         do_test_drop_messages_peer_disconnect(3);
3387 }
3388
3389 #[test]
3390 fn test_drop_messages_peer_disconnect_b() {
3391         do_test_drop_messages_peer_disconnect(4);
3392         do_test_drop_messages_peer_disconnect(5);
3393         do_test_drop_messages_peer_disconnect(6);
3394 }
3395
3396 #[test]
3397 fn test_funding_peer_disconnect() {
3398         // Test that we can lock in our funding tx while disconnected
3399         let chanmon_cfgs = create_chanmon_cfgs(2);
3400         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3401         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3402         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3403         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::supported(), InitFeatures::supported());
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
3408         confirm_transaction(&nodes[0].block_notifier, &nodes[0].chain_monitor, &tx, tx.version);
3409         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3410         assert_eq!(events_1.len(), 1);
3411         match events_1[0] {
3412                 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3413                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3414                 },
3415                 _ => panic!("Unexpected event"),
3416         }
3417
3418         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3419
3420         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3421         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3422
3423         confirm_transaction(&nodes[1].block_notifier, &nodes[1].chain_monitor, &tx, tx.version);
3424         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3425         assert_eq!(events_2.len(), 2);
3426         let funding_locked = match events_2[0] {
3427                 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3428                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3429                         msg.clone()
3430                 },
3431                 _ => panic!("Unexpected event"),
3432         };
3433         let bs_announcement_sigs = match events_2[1] {
3434                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3435                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3436                         msg.clone()
3437                 },
3438                 _ => panic!("Unexpected event"),
3439         };
3440
3441         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3442
3443         nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3444         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3445         let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3446         assert_eq!(events_3.len(), 2);
3447         let as_announcement_sigs = match events_3[0] {
3448                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3449                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3450                         msg.clone()
3451                 },
3452                 _ => panic!("Unexpected event"),
3453         };
3454         let (as_announcement, as_update) = match events_3[1] {
3455                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3456                         (msg.clone(), update_msg.clone())
3457                 },
3458                 _ => panic!("Unexpected event"),
3459         };
3460
3461         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3462         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3463         assert_eq!(events_4.len(), 1);
3464         let (_, bs_update) = match events_4[0] {
3465                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3466                         (msg.clone(), update_msg.clone())
3467                 },
3468                 _ => panic!("Unexpected event"),
3469         };
3470
3471         nodes[0].router.handle_channel_announcement(&as_announcement).unwrap();
3472         nodes[0].router.handle_channel_update(&bs_update).unwrap();
3473         nodes[0].router.handle_channel_update(&as_update).unwrap();
3474
3475         let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
3476         let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3477         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage, 1_000_000);
3478 }
3479
3480 #[test]
3481 fn test_drop_messages_peer_disconnect_dual_htlc() {
3482         // Test that we can handle reconnecting when both sides of a channel have pending
3483         // commitment_updates when we disconnect.
3484         let chanmon_cfgs = create_chanmon_cfgs(2);
3485         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3486         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3487         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3488         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
3489
3490         let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3491
3492         // Now try to send a second payment which will fail to send
3493         let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
3494         let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
3495
3496         nodes[0].node.send_payment(route.clone(), payment_hash_2).unwrap();
3497         check_added_monitors!(nodes[0], 1);
3498
3499         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3500         assert_eq!(events_1.len(), 1);
3501         match events_1[0] {
3502                 MessageSendEvent::UpdateHTLCs { .. } => {},
3503                 _ => panic!("Unexpected event"),
3504         }
3505
3506         assert!(nodes[1].node.claim_funds(payment_preimage_1, 1_000_000));
3507         check_added_monitors!(nodes[1], 1);
3508
3509         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3510         assert_eq!(events_2.len(), 1);
3511         match events_2[0] {
3512                 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 } } => {
3513                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3514                         assert!(update_add_htlcs.is_empty());
3515                         assert_eq!(update_fulfill_htlcs.len(), 1);
3516                         assert!(update_fail_htlcs.is_empty());
3517                         assert!(update_fail_malformed_htlcs.is_empty());
3518                         assert!(update_fee.is_none());
3519
3520                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3521                         let events_3 = nodes[0].node.get_and_clear_pending_events();
3522                         assert_eq!(events_3.len(), 1);
3523                         match events_3[0] {
3524                                 Event::PaymentSent { ref payment_preimage } => {
3525                                         assert_eq!(*payment_preimage, payment_preimage_1);
3526                                 },
3527                                 _ => panic!("Unexpected event"),
3528                         }
3529
3530                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3531                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3532                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3533                         check_added_monitors!(nodes[0], 1);
3534                 },
3535                 _ => panic!("Unexpected event"),
3536         }
3537
3538         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3539         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3540
3541         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3542         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3543         assert_eq!(reestablish_1.len(), 1);
3544         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3545         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3546         assert_eq!(reestablish_2.len(), 1);
3547
3548         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3549         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3550         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3551         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3552
3553         assert!(as_resp.0.is_none());
3554         assert!(bs_resp.0.is_none());
3555
3556         assert!(bs_resp.1.is_none());
3557         assert!(bs_resp.2.is_none());
3558
3559         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3560
3561         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3562         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3563         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3564         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3565         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3566         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
3567         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
3568         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3569         // No commitment_signed so get_event_msg's assert(len == 1) passes
3570         check_added_monitors!(nodes[1], 1);
3571
3572         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
3573         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3574         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3575         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3576         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3577         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3578         assert!(bs_second_commitment_signed.update_fee.is_none());
3579         check_added_monitors!(nodes[1], 1);
3580
3581         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3582         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3583         assert!(as_commitment_signed.update_add_htlcs.is_empty());
3584         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
3585         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
3586         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
3587         assert!(as_commitment_signed.update_fee.is_none());
3588         check_added_monitors!(nodes[0], 1);
3589
3590         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
3591         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3592         // No commitment_signed so get_event_msg's assert(len == 1) passes
3593         check_added_monitors!(nodes[0], 1);
3594
3595         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
3596         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3597         // No commitment_signed so get_event_msg's assert(len == 1) passes
3598         check_added_monitors!(nodes[1], 1);
3599
3600         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3601         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3602         check_added_monitors!(nodes[1], 1);
3603
3604         expect_pending_htlcs_forwardable!(nodes[1]);
3605
3606         let events_5 = nodes[1].node.get_and_clear_pending_events();
3607         assert_eq!(events_5.len(), 1);
3608         match events_5[0] {
3609                 Event::PaymentReceived { ref payment_hash, amt: _ } => {
3610                         assert_eq!(payment_hash_2, *payment_hash);
3611                 },
3612                 _ => panic!("Unexpected event"),
3613         }
3614
3615         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
3616         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3617         check_added_monitors!(nodes[0], 1);
3618
3619         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3620 }
3621
3622 #[test]
3623 fn test_invalid_channel_announcement() {
3624         //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
3625         let secp_ctx = Secp256k1::new();
3626         let chanmon_cfgs = create_chanmon_cfgs(2);
3627         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3628         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3629         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3630
3631         let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::supported(), InitFeatures::supported());
3632
3633         let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
3634         let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
3635         let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
3636         let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
3637
3638         nodes[0].router.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id : as_chan.get_short_channel_id().unwrap(), is_permanent: false } );
3639
3640         let as_bitcoin_key = as_chan.get_local_keys().inner.local_channel_pubkeys.funding_pubkey;
3641         let bs_bitcoin_key = bs_chan.get_local_keys().inner.local_channel_pubkeys.funding_pubkey;
3642
3643         let as_network_key = nodes[0].node.get_our_node_id();
3644         let bs_network_key = nodes[1].node.get_our_node_id();
3645
3646         let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
3647
3648         let mut chan_announcement;
3649
3650         macro_rules! dummy_unsigned_msg {
3651                 () => {
3652                         msgs::UnsignedChannelAnnouncement {
3653                                 features: ChannelFeatures::supported(),
3654                                 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
3655                                 short_channel_id: as_chan.get_short_channel_id().unwrap(),
3656                                 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
3657                                 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
3658                                 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
3659                                 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
3660                                 excess_data: Vec::new(),
3661                         };
3662                 }
3663         }
3664
3665         macro_rules! sign_msg {
3666                 ($unsigned_msg: expr) => {
3667                         let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
3668                         let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_local_keys().inner.funding_key());
3669                         let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_local_keys().inner.funding_key());
3670                         let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
3671                         let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
3672                         chan_announcement = msgs::ChannelAnnouncement {
3673                                 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
3674                                 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
3675                                 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
3676                                 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
3677                                 contents: $unsigned_msg
3678                         }
3679                 }
3680         }
3681
3682         let unsigned_msg = dummy_unsigned_msg!();
3683         sign_msg!(unsigned_msg);
3684         assert_eq!(nodes[0].router.handle_channel_announcement(&chan_announcement).unwrap(), true);
3685         let _ = nodes[0].router.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id : as_chan.get_short_channel_id().unwrap(), is_permanent: false } );
3686
3687         // Configured with Network::Testnet
3688         let mut unsigned_msg = dummy_unsigned_msg!();
3689         unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.bitcoin_hash();
3690         sign_msg!(unsigned_msg);
3691         assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
3692
3693         let mut unsigned_msg = dummy_unsigned_msg!();
3694         unsigned_msg.chain_hash = Sha256dHash::hash(&[1,2,3,4,5,6,7,8,9]);
3695         sign_msg!(unsigned_msg);
3696         assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
3697 }
3698
3699 #[test]
3700 fn test_no_txn_manager_serialize_deserialize() {
3701         let chanmon_cfgs = create_chanmon_cfgs(2);
3702         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3703         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3704         let fee_estimator: test_utils::TestFeeEstimator;
3705         let new_chan_monitor: test_utils::TestChannelMonitor;
3706         let keys_manager: test_utils::TestKeysInterface;
3707         let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>;
3708         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3709
3710         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::supported(), InitFeatures::supported());
3711
3712         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3713
3714         let nodes_0_serialized = nodes[0].node.encode();
3715         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3716         nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
3717
3718         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
3719         new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), Arc::new(test_utils::TestLogger::new()), &fee_estimator);
3720         nodes[0].chan_monitor = &new_chan_monitor;
3721         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3722         let (_, mut chan_0_monitor) = <(Sha256dHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
3723         assert!(chan_0_monitor_read.is_empty());
3724
3725         let mut nodes_0_read = &nodes_0_serialized[..];
3726         let config = UserConfig::default();
3727         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new()));
3728         let (_, nodes_0_deserialized_tmp) = {
3729                 let mut channel_monitors = HashMap::new();
3730                 channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &mut chan_0_monitor);
3731                 <(Sha256dHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3732                         default_config: config,
3733                         keys_manager: &keys_manager,
3734                         fee_estimator: &fee_estimator,
3735                         monitor: nodes[0].chan_monitor,
3736                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3737                         logger: Arc::new(test_utils::TestLogger::new()),
3738                         channel_monitors: &mut channel_monitors,
3739                 }).unwrap()
3740         };
3741         nodes_0_deserialized = nodes_0_deserialized_tmp;
3742         assert!(nodes_0_read.is_empty());
3743
3744         assert!(nodes[0].chan_monitor.add_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
3745         nodes[0].node = &nodes_0_deserialized;
3746         nodes[0].block_notifier.register_listener(nodes[0].node);
3747         assert_eq!(nodes[0].node.list_channels().len(), 1);
3748         check_added_monitors!(nodes[0], 1);
3749
3750         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3751         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3752         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3753         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3754
3755         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3756         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3757         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3758         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3759
3760         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
3761         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
3762         for node in nodes.iter() {
3763                 assert!(node.router.handle_channel_announcement(&announcement).unwrap());
3764                 node.router.handle_channel_update(&as_update).unwrap();
3765                 node.router.handle_channel_update(&bs_update).unwrap();
3766         }
3767
3768         send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
3769 }
3770
3771 #[test]
3772 fn test_simple_manager_serialize_deserialize() {
3773         let chanmon_cfgs = create_chanmon_cfgs(2);
3774         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3775         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3776         let fee_estimator: test_utils::TestFeeEstimator;
3777         let new_chan_monitor: test_utils::TestChannelMonitor;
3778         let keys_manager: test_utils::TestKeysInterface;
3779         let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>;
3780         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3781         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
3782
3783         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3784         let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3785
3786         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3787
3788         let nodes_0_serialized = nodes[0].node.encode();
3789         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3790         nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
3791
3792         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
3793         new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), Arc::new(test_utils::TestLogger::new()), &fee_estimator);
3794         nodes[0].chan_monitor = &new_chan_monitor;
3795         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3796         let (_, mut chan_0_monitor) = <(Sha256dHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
3797         assert!(chan_0_monitor_read.is_empty());
3798
3799         let mut nodes_0_read = &nodes_0_serialized[..];
3800         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new()));
3801         let (_, nodes_0_deserialized_tmp) = {
3802                 let mut channel_monitors = HashMap::new();
3803                 channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &mut chan_0_monitor);
3804                 <(Sha256dHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3805                         default_config: UserConfig::default(),
3806                         keys_manager: &keys_manager,
3807                         fee_estimator: &fee_estimator,
3808                         monitor: nodes[0].chan_monitor,
3809                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3810                         logger: Arc::new(test_utils::TestLogger::new()),
3811                         channel_monitors: &mut channel_monitors,
3812                 }).unwrap()
3813         };
3814         nodes_0_deserialized = nodes_0_deserialized_tmp;
3815         assert!(nodes_0_read.is_empty());
3816
3817         assert!(nodes[0].chan_monitor.add_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
3818         nodes[0].node = &nodes_0_deserialized;
3819         check_added_monitors!(nodes[0], 1);
3820
3821         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3822
3823         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
3824         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage, 1_000_000);
3825 }
3826
3827 #[test]
3828 fn test_manager_serialize_deserialize_inconsistent_monitor() {
3829         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
3830         let chanmon_cfgs = create_chanmon_cfgs(4);
3831         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3832         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
3833         let fee_estimator: test_utils::TestFeeEstimator;
3834         let new_chan_monitor: test_utils::TestChannelMonitor;
3835         let keys_manager: test_utils::TestKeysInterface;
3836         let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>;
3837         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3838         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
3839         create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::supported(), InitFeatures::supported());
3840         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::supported(), InitFeatures::supported());
3841
3842         let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
3843
3844         // Serialize the ChannelManager here, but the monitor we keep up-to-date
3845         let nodes_0_serialized = nodes[0].node.encode();
3846
3847         route_payment(&nodes[0], &[&nodes[3]], 1000000);
3848         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3849         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3850         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3851
3852         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
3853         // nodes[3])
3854         let mut node_0_monitors_serialized = Vec::new();
3855         for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
3856                 let mut writer = test_utils::TestVecWriter(Vec::new());
3857                 monitor.1.write_for_disk(&mut writer).unwrap();
3858                 node_0_monitors_serialized.push(writer.0);
3859         }
3860
3861         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
3862         new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), Arc::new(test_utils::TestLogger::new()), &fee_estimator);
3863         nodes[0].chan_monitor = &new_chan_monitor;
3864         let mut node_0_monitors = Vec::new();
3865         for serialized in node_0_monitors_serialized.iter() {
3866                 let mut read = &serialized[..];
3867                 let (_, monitor) = <(Sha256dHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read, Arc::new(test_utils::TestLogger::new())).unwrap();
3868                 assert!(read.is_empty());
3869                 node_0_monitors.push(monitor);
3870         }
3871
3872         let mut nodes_0_read = &nodes_0_serialized[..];
3873         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new()));
3874         let (_, nodes_0_deserialized_tmp) = <(Sha256dHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3875                 default_config: UserConfig::default(),
3876                 keys_manager: &keys_manager,
3877                 fee_estimator: &fee_estimator,
3878                 monitor: nodes[0].chan_monitor,
3879                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3880                 logger: Arc::new(test_utils::TestLogger::new()),
3881                 channel_monitors: &mut node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().unwrap(), monitor) }).collect(),
3882         }).unwrap();
3883         nodes_0_deserialized = nodes_0_deserialized_tmp;
3884         assert!(nodes_0_read.is_empty());
3885
3886         { // Channel close should result in a commitment tx and an HTLC tx
3887                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3888                 assert_eq!(txn.len(), 2);
3889                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
3890                 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
3891         }
3892
3893         for monitor in node_0_monitors.drain(..) {
3894                 assert!(nodes[0].chan_monitor.add_monitor(monitor.get_funding_txo().unwrap(), monitor).is_ok());
3895                 check_added_monitors!(nodes[0], 1);
3896         }
3897         nodes[0].node = &nodes_0_deserialized;
3898
3899         // nodes[1] and nodes[2] have no lost state with nodes[0]...
3900         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3901         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3902         //... and we can even still claim the payment!
3903         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage, 1_000_000);
3904
3905         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3906         let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
3907         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3908         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
3909         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
3910         assert_eq!(msg_events.len(), 1);
3911         if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
3912                 match action {
3913                         &ErrorAction::SendErrorMessage { ref msg } => {
3914                                 assert_eq!(msg.channel_id, channel_id);
3915                         },
3916                         _ => panic!("Unexpected event!"),
3917                 }
3918         }
3919 }
3920
3921 macro_rules! check_spendable_outputs {
3922         ($node: expr, $der_idx: expr) => {
3923                 {
3924                         let events = $node.chan_monitor.simple_monitor.get_and_clear_pending_events();
3925                         let mut txn = Vec::new();
3926                         for event in events {
3927                                 match event {
3928                                         Event::SpendableOutputs { ref outputs } => {
3929                                                 for outp in outputs {
3930                                                         match *outp {
3931                                                                 SpendableOutputDescriptor::DynamicOutputP2WPKH { ref outpoint, ref key, ref output } => {
3932                                                                         let input = TxIn {
3933                                                                                 previous_output: outpoint.clone(),
3934                                                                                 script_sig: Script::new(),
3935                                                                                 sequence: 0,
3936                                                                                 witness: Vec::new(),
3937                                                                         };
3938                                                                         let outp = TxOut {
3939                                                                                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
3940                                                                                 value: output.value,
3941                                                                         };
3942                                                                         let mut spend_tx = Transaction {
3943                                                                                 version: 2,
3944                                                                                 lock_time: 0,
3945                                                                                 input: vec![input],
3946                                                                                 output: vec![outp],
3947                                                                         };
3948                                                                         let secp_ctx = Secp256k1::new();
3949                                                                         let remotepubkey = PublicKey::from_secret_key(&secp_ctx, &key);
3950                                                                         let witness_script = Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: remotepubkey}, Network::Testnet).script_pubkey();
3951                                                                         let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
3952                                                                         let remotesig = secp_ctx.sign(&sighash, key);
3953                                                                         spend_tx.input[0].witness.push(remotesig.serialize_der().to_vec());
3954                                                                         spend_tx.input[0].witness[0].push(SigHashType::All as u8);
3955                                                                         spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
3956                                                                         txn.push(spend_tx);
3957                                                                 },
3958                                                                 SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref key, ref witness_script, ref to_self_delay, ref output } => {
3959                                                                         let input = TxIn {
3960                                                                                 previous_output: outpoint.clone(),
3961                                                                                 script_sig: Script::new(),
3962                                                                                 sequence: *to_self_delay as u32,
3963                                                                                 witness: Vec::new(),
3964                                                                         };
3965                                                                         let outp = TxOut {
3966                                                                                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
3967                                                                                 value: output.value,
3968                                                                         };
3969                                                                         let mut spend_tx = Transaction {
3970                                                                                 version: 2,
3971                                                                                 lock_time: 0,
3972                                                                                 input: vec![input],
3973                                                                                 output: vec![outp],
3974                                                                         };
3975                                                                         let secp_ctx = Secp256k1::new();
3976                                                                         let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], witness_script, output.value)[..]).unwrap();
3977                                                                         let local_delaysig = secp_ctx.sign(&sighash, key);
3978                                                                         spend_tx.input[0].witness.push(local_delaysig.serialize_der().to_vec());
3979                                                                         spend_tx.input[0].witness[0].push(SigHashType::All as u8);
3980                                                                         spend_tx.input[0].witness.push(vec!(0));
3981                                                                         spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
3982                                                                         txn.push(spend_tx);
3983                                                                 },
3984                                                                 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
3985                                                                         let secp_ctx = Secp256k1::new();
3986                                                                         let input = TxIn {
3987                                                                                 previous_output: outpoint.clone(),
3988                                                                                 script_sig: Script::new(),
3989                                                                                 sequence: 0,
3990                                                                                 witness: Vec::new(),
3991                                                                         };
3992                                                                         let outp = TxOut {
3993                                                                                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
3994                                                                                 value: output.value,
3995                                                                         };
3996                                                                         let mut spend_tx = Transaction {
3997                                                                                 version: 2,
3998                                                                                 lock_time: 0,
3999                                                                                 input: vec![input],
4000                                                                                 output: vec![outp.clone()],
4001                                                                         };
4002                                                                         let secret = {
4003                                                                                 match ExtendedPrivKey::new_master(Network::Testnet, &$node.node_seed) {
4004                                                                                         Ok(master_key) => {
4005                                                                                                 match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx).expect("key space exhausted")) {
4006                                                                                                         Ok(key) => key,
4007                                                                                                         Err(_) => panic!("Your RNG is busted"),
4008                                                                                                 }
4009                                                                                         }
4010                                                                                         Err(_) => panic!("Your rng is busted"),
4011                                                                                 }
4012                                                                         };
4013                                                                         let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
4014                                                                         let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
4015                                                                         let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
4016                                                                         let sig = secp_ctx.sign(&sighash, &secret.private_key.key);
4017                                                                         spend_tx.input[0].witness.push(sig.serialize_der().to_vec());
4018                                                                         spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4019                                                                         spend_tx.input[0].witness.push(pubkey.key.serialize().to_vec());
4020                                                                         txn.push(spend_tx);
4021                                                                 },
4022                                                         }
4023                                                 }
4024                                         },
4025                                         _ => panic!("Unexpected event"),
4026                                 };
4027                         }
4028                         txn
4029                 }
4030         }
4031 }
4032
4033 #[test]
4034 fn test_claim_sizeable_push_msat() {
4035         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4036         let chanmon_cfgs = create_chanmon_cfgs(2);
4037         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4038         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4039         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4040
4041         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::supported(), InitFeatures::supported());
4042         nodes[1].node.force_close_channel(&chan.2);
4043         check_closed_broadcast!(nodes[1], false);
4044         check_added_monitors!(nodes[1], 1);
4045         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4046         assert_eq!(node_txn.len(), 1);
4047         check_spends!(node_txn[0], chan.3);
4048         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
4049
4050         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4051         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4052         let spend_txn = check_spendable_outputs!(nodes[1], 1);
4053         assert_eq!(spend_txn.len(), 1);
4054         check_spends!(spend_txn[0], node_txn[0]);
4055 }
4056
4057 #[test]
4058 fn test_claim_on_remote_sizeable_push_msat() {
4059         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4060         // to_remote output is encumbered by a P2WPKH
4061         let chanmon_cfgs = create_chanmon_cfgs(2);
4062         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4063         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4064         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4065
4066         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::supported(), InitFeatures::supported());
4067         nodes[0].node.force_close_channel(&chan.2);
4068         check_closed_broadcast!(nodes[0], false);
4069         check_added_monitors!(nodes[0], 1);
4070
4071         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4072         assert_eq!(node_txn.len(), 1);
4073         check_spends!(node_txn[0], chan.3);
4074         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
4075
4076         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4077         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4078         check_closed_broadcast!(nodes[1], false);
4079         check_added_monitors!(nodes[1], 1);
4080         let spend_txn = check_spendable_outputs!(nodes[1], 1);
4081         assert_eq!(spend_txn.len(), 2);
4082         assert_eq!(spend_txn[0], spend_txn[1]);
4083         check_spends!(spend_txn[0], node_txn[0]);
4084 }
4085
4086 #[test]
4087 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4088         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4089         // to_remote output is encumbered by a P2WPKH
4090
4091         let chanmon_cfgs = create_chanmon_cfgs(2);
4092         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4093         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4094         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4095
4096         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::supported(), InitFeatures::supported());
4097         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4098         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4099         assert_eq!(revoked_local_txn[0].input.len(), 1);
4100         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4101
4102         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4103         let  header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4104         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4105         check_closed_broadcast!(nodes[1], false);
4106         check_added_monitors!(nodes[1], 1);
4107
4108         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4109         let spend_txn = check_spendable_outputs!(nodes[1], 1);
4110         assert_eq!(spend_txn.len(), 3);
4111         assert_eq!(spend_txn[0], spend_txn[2]); // to_remote output on revoked remote commitment_tx
4112         check_spends!(spend_txn[0], revoked_local_txn[0]);
4113         check_spends!(spend_txn[1], node_txn[0]);
4114 }
4115
4116 #[test]
4117 fn test_static_spendable_outputs_preimage_tx() {
4118         let chanmon_cfgs = create_chanmon_cfgs(2);
4119         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4120         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4121         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4122
4123         // Create some initial channels
4124         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4125
4126         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4127
4128         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4129         assert_eq!(commitment_tx[0].input.len(), 1);
4130         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4131
4132         // Settle A's commitment tx on B's chain
4133         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4134         assert!(nodes[1].node.claim_funds(payment_preimage, 3_000_000));
4135         check_added_monitors!(nodes[1], 1);
4136         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
4137         check_added_monitors!(nodes[1], 1);
4138         let events = nodes[1].node.get_and_clear_pending_msg_events();
4139         match events[0] {
4140                 MessageSendEvent::UpdateHTLCs { .. } => {},
4141                 _ => panic!("Unexpected event"),
4142         }
4143         match events[1] {
4144                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4145                 _ => panic!("Unexepected event"),
4146         }
4147
4148         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4149         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4150         assert_eq!(node_txn.len(), 3);
4151         check_spends!(node_txn[0], commitment_tx[0]);
4152         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4153 eprintln!("{:?}", node_txn[1]);
4154         check_spends!(node_txn[1], chan_1.3);
4155         check_spends!(node_txn[2], node_txn[1]);
4156
4157         let spend_txn = check_spendable_outputs!(nodes[1], 1); // , 0, 0, 1, 1);
4158         assert_eq!(spend_txn.len(), 1);
4159         check_spends!(spend_txn[0], node_txn[0]);
4160 }
4161
4162 #[test]
4163 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4164         let chanmon_cfgs = create_chanmon_cfgs(2);
4165         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4166         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4167         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4168
4169         // Create some initial channels
4170         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4171
4172         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4173         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4174         assert_eq!(revoked_local_txn[0].input.len(), 1);
4175         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4176
4177         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4178
4179         let  header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4180         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4181         check_closed_broadcast!(nodes[1], false);
4182         check_added_monitors!(nodes[1], 1);
4183
4184         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4185         assert_eq!(node_txn.len(), 2);
4186         assert_eq!(node_txn[0].input.len(), 2);
4187         check_spends!(node_txn[0], revoked_local_txn[0]);
4188
4189         let spend_txn = check_spendable_outputs!(nodes[1], 1);
4190         assert_eq!(spend_txn.len(), 1);
4191         check_spends!(spend_txn[0], node_txn[0]);
4192 }
4193
4194 #[test]
4195 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4196         let chanmon_cfgs = create_chanmon_cfgs(2);
4197         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4198         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4199         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4200
4201         // Create some initial channels
4202         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4203
4204         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4205         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4206         assert_eq!(revoked_local_txn[0].input.len(), 1);
4207         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4208
4209         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4210
4211         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4212         // A will generate HTLC-Timeout from revoked commitment tx
4213         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4214         check_closed_broadcast!(nodes[0], false);
4215         check_added_monitors!(nodes[0], 1);
4216
4217         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4218         assert_eq!(revoked_htlc_txn.len(), 3);
4219         assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
4220         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4221         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4222         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4223         check_spends!(revoked_htlc_txn[1], chan_1.3);
4224
4225         // B will generate justice tx from A's revoked commitment/HTLC tx
4226         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
4227         check_closed_broadcast!(nodes[1], false);
4228         check_added_monitors!(nodes[1], 1);
4229
4230         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4231         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
4232         assert_eq!(node_txn[0].input.len(), 2);
4233         check_spends!(node_txn[0], revoked_local_txn[0]);
4234         check_spends!(node_txn[1], chan_1.3);
4235         assert_eq!(node_txn[2].input.len(), 1);
4236         check_spends!(node_txn[2], revoked_htlc_txn[0]);
4237         assert_eq!(node_txn[3].input.len(), 1);
4238         check_spends!(node_txn[3], revoked_local_txn[0]);
4239
4240         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4241         let spend_txn = check_spendable_outputs!(nodes[1], 1);
4242         assert_eq!(spend_txn.len(), 2);
4243         check_spends!(spend_txn[0], node_txn[0]);
4244         check_spends!(spend_txn[1], node_txn[2]);
4245 }
4246
4247 #[test]
4248 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4249         let chanmon_cfgs = create_chanmon_cfgs(2);
4250         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4251         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4252         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4253
4254         // Create some initial channels
4255         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4256
4257         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4258         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4259         assert_eq!(revoked_local_txn[0].input.len(), 1);
4260         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4261
4262         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4263
4264         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4265         // B will generate HTLC-Success from revoked commitment tx
4266         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4267         check_closed_broadcast!(nodes[1], false);
4268         check_added_monitors!(nodes[1], 1);
4269         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4270
4271         assert_eq!(revoked_htlc_txn.len(), 3);
4272         assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
4273         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4274         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4275         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4276
4277         // A will generate justice tx from B's revoked commitment/HTLC tx
4278         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
4279         check_closed_broadcast!(nodes[0], false);
4280         check_added_monitors!(nodes[0], 1);
4281
4282         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4283         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
4284         assert_eq!(node_txn[2].input.len(), 1);
4285         check_spends!(node_txn[2], revoked_htlc_txn[0]);
4286
4287         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4288         let spend_txn = check_spendable_outputs!(nodes[0], 1);
4289         assert_eq!(spend_txn.len(), 5); // Duplicated SpendableOutput due to block rescan after revoked htlc output tracking
4290         assert_eq!(spend_txn[0], spend_txn[2]);
4291         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4292         check_spends!(spend_txn[1], node_txn[0]); // spending justice tx output from revoked local tx htlc received output
4293         check_spends!(spend_txn[3], node_txn[2]); // spending justice tx output on htlc success tx
4294 }
4295
4296 #[test]
4297 fn test_onchain_to_onchain_claim() {
4298         // Test that in case of channel closure, we detect the state of output thanks to
4299         // ChainWatchInterface and claim HTLC on downstream peer's remote commitment tx.
4300         // First, have C claim an HTLC against its own latest commitment transaction.
4301         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4302         // channel.
4303         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4304         // gets broadcast.
4305
4306         let chanmon_cfgs = create_chanmon_cfgs(3);
4307         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4308         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4309         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4310
4311         // Create some initial channels
4312         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4313         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
4314
4315         // Rebalance the network a bit by relaying one payment through all the channels ...
4316         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
4317         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
4318
4319         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
4320         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
4321         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4322         check_spends!(commitment_tx[0], chan_2.3);
4323         nodes[2].node.claim_funds(payment_preimage, 3_000_000);
4324         check_added_monitors!(nodes[2], 1);
4325         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4326         assert!(updates.update_add_htlcs.is_empty());
4327         assert!(updates.update_fail_htlcs.is_empty());
4328         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4329         assert!(updates.update_fail_malformed_htlcs.is_empty());
4330
4331         nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
4332         check_closed_broadcast!(nodes[2], false);
4333         check_added_monitors!(nodes[2], 1);
4334
4335         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
4336         assert_eq!(c_txn.len(), 4);
4337         assert_eq!(c_txn[0], c_txn[2]);
4338         assert_eq!(c_txn[0], c_txn[3]);
4339         assert_eq!(commitment_tx[0], c_txn[1]);
4340         check_spends!(c_txn[1], chan_2.3);
4341         check_spends!(c_txn[2], c_txn[1]);
4342         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
4343         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4344         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4345         assert_eq!(c_txn[0].lock_time, 0); // Success tx
4346
4347         // 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
4348         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
4349         {
4350                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4351                 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-timeout tx
4352                 assert_eq!(b_txn.len(), 3);
4353                 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
4354                 check_spends!(b_txn[2], b_txn[1]); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
4355                 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4356                 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4357                 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
4358                 check_spends!(b_txn[0], c_txn[1]); // timeout tx on C remote commitment tx, issued by ChannelMonitor, * 2 due to block rescan
4359                 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4360                 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4361                 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
4362                 b_txn.clear();
4363         }
4364         check_added_monitors!(nodes[1], 1);
4365         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4366         check_added_monitors!(nodes[1], 1);
4367         match msg_events[0] {
4368                 MessageSendEvent::BroadcastChannelUpdate {  .. } => {},
4369                 _ => panic!("Unexpected event"),
4370         }
4371         match msg_events[1] {
4372                 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, .. } } => {
4373                         assert!(update_add_htlcs.is_empty());
4374                         assert!(update_fail_htlcs.is_empty());
4375                         assert_eq!(update_fulfill_htlcs.len(), 1);
4376                         assert!(update_fail_malformed_htlcs.is_empty());
4377                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4378                 },
4379                 _ => panic!("Unexpected event"),
4380         };
4381         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4382         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4383         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
4384         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4385         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
4386         assert_eq!(b_txn.len(), 3);
4387         check_spends!(b_txn[1], chan_1.3);
4388         check_spends!(b_txn[2], b_txn[1]);
4389         check_spends!(b_txn[0], commitment_tx[0]);
4390         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4391         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4392         assert_eq!(b_txn[0].lock_time, 0); // Success tx
4393
4394         check_closed_broadcast!(nodes[1], false);
4395         check_added_monitors!(nodes[1], 1);
4396 }
4397
4398 #[test]
4399 fn test_duplicate_payment_hash_one_failure_one_success() {
4400         // Topology : A --> B --> C
4401         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4402         let chanmon_cfgs = create_chanmon_cfgs(3);
4403         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4404         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4405         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4406
4407         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4408         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
4409
4410         let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
4411         *nodes[0].network_payment_count.borrow_mut() -= 1;
4412         assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
4413
4414         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4415         assert_eq!(commitment_txn[0].input.len(), 1);
4416         check_spends!(commitment_txn[0], chan_2.3);
4417
4418         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4419         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
4420         check_closed_broadcast!(nodes[1], false);
4421         check_added_monitors!(nodes[1], 1);
4422
4423         let htlc_timeout_tx;
4424         { // Extract one of the two HTLC-Timeout transaction
4425                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4426                 // ChannelMonitor: timeout tx * 2, ChannelManager: local commitment tx + HTLC-timeout * 2
4427                 assert_eq!(node_txn.len(), 5);
4428                 check_spends!(node_txn[0], commitment_txn[0]);
4429                 assert_eq!(node_txn[0].input.len(), 1);
4430                 check_spends!(node_txn[1], commitment_txn[0]);
4431                 assert_eq!(node_txn[1].input.len(), 1);
4432                 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
4433                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4434                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4435                 check_spends!(node_txn[2], chan_2.3);
4436                 check_spends!(node_txn[3], node_txn[2]);
4437                 check_spends!(node_txn[4], node_txn[2]);
4438                 htlc_timeout_tx = node_txn[1].clone();
4439         }
4440
4441         nodes[2].node.claim_funds(our_payment_preimage, 900_000);
4442         nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
4443         check_added_monitors!(nodes[2], 3);
4444         let events = nodes[2].node.get_and_clear_pending_msg_events();
4445         match events[0] {
4446                 MessageSendEvent::UpdateHTLCs { .. } => {},
4447                 _ => panic!("Unexpected event"),
4448         }
4449         match events[1] {
4450                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4451                 _ => panic!("Unexepected event"),
4452         }
4453         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4454         assert_eq!(htlc_success_txn.len(), 7);
4455         check_spends!(htlc_success_txn[2], chan_2.3);
4456         check_spends!(htlc_success_txn[3], htlc_success_txn[2]);
4457         check_spends!(htlc_success_txn[4], htlc_success_txn[2]);
4458         assert_eq!(htlc_success_txn[0], htlc_success_txn[5]);
4459         assert_eq!(htlc_success_txn[0].input.len(), 1);
4460         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4461         assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
4462         assert_eq!(htlc_success_txn[1].input.len(), 1);
4463         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4464         assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
4465         check_spends!(htlc_success_txn[0], commitment_txn[0]);
4466         check_spends!(htlc_success_txn[1], commitment_txn[0]);
4467
4468         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![htlc_timeout_tx] }, 200);
4469         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 200, true, header.bitcoin_hash());
4470         expect_pending_htlcs_forwardable!(nodes[1]);
4471         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4472         assert!(htlc_updates.update_add_htlcs.is_empty());
4473         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4474         assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
4475         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4476         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4477         check_added_monitors!(nodes[1], 1);
4478
4479         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4480         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4481         {
4482                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4483                 let events = nodes[0].node.get_and_clear_pending_msg_events();
4484                 assert_eq!(events.len(), 1);
4485                 match events[0] {
4486                         MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. }  } => {
4487                         },
4488                         _ => { panic!("Unexpected event"); }
4489                 }
4490         }
4491         let events = nodes[0].node.get_and_clear_pending_events();
4492         match events[0] {
4493                 Event::PaymentFailed { ref payment_hash, .. } => {
4494                         assert_eq!(*payment_hash, duplicate_payment_hash);
4495                 }
4496                 _ => panic!("Unexpected event"),
4497         }
4498
4499         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4500         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
4501         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4502         assert!(updates.update_add_htlcs.is_empty());
4503         assert!(updates.update_fail_htlcs.is_empty());
4504         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4505         assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
4506         assert!(updates.update_fail_malformed_htlcs.is_empty());
4507         check_added_monitors!(nodes[1], 1);
4508
4509         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4510         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4511
4512         let events = nodes[0].node.get_and_clear_pending_events();
4513         match events[0] {
4514                 Event::PaymentSent { ref payment_preimage } => {
4515                         assert_eq!(*payment_preimage, our_payment_preimage);
4516                 }
4517                 _ => panic!("Unexpected event"),
4518         }
4519 }
4520
4521 #[test]
4522 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4523         let chanmon_cfgs = create_chanmon_cfgs(2);
4524         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4525         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4526         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4527
4528         // Create some initial channels
4529         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4530
4531         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
4532         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4533         assert_eq!(local_txn[0].input.len(), 1);
4534         check_spends!(local_txn[0], chan_1.3);
4535
4536         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4537         nodes[1].node.claim_funds(payment_preimage, 9_000_000);
4538         check_added_monitors!(nodes[1], 1);
4539         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4540         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![local_txn[0].clone()] }, 1);
4541         check_added_monitors!(nodes[1], 1);
4542         let events = nodes[1].node.get_and_clear_pending_msg_events();
4543         match events[0] {
4544                 MessageSendEvent::UpdateHTLCs { .. } => {},
4545                 _ => panic!("Unexpected event"),
4546         }
4547         match events[1] {
4548                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4549                 _ => panic!("Unexepected event"),
4550         }
4551         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4552         assert_eq!(node_txn[0].input.len(), 1);
4553         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4554         check_spends!(node_txn[0], local_txn[0]);
4555
4556         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4557         let spend_txn = check_spendable_outputs!(nodes[1], 1);
4558         assert_eq!(spend_txn.len(), 2);
4559         check_spends!(spend_txn[0], node_txn[0]);
4560         check_spends!(spend_txn[1], node_txn[2]);
4561 }
4562
4563 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4564         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4565         // unrevoked commitment transaction.
4566         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4567         // a remote RAA before they could be failed backwards (and combinations thereof).
4568         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4569         // use the same payment hashes.
4570         // Thus, we use a six-node network:
4571         //
4572         // A \         / E
4573         //    - C - D -
4574         // B /         \ F
4575         // And test where C fails back to A/B when D announces its latest commitment transaction
4576         let chanmon_cfgs = create_chanmon_cfgs(6);
4577         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
4578         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
4579         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
4580
4581         create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::supported(), InitFeatures::supported());
4582         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
4583         let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::supported(), InitFeatures::supported());
4584         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::supported(), InitFeatures::supported());
4585         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::supported(), InitFeatures::supported());
4586
4587         // Rebalance and check output sanity...
4588         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000, 500_000);
4589         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000, 500_000);
4590         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
4591
4592         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
4593         // 0th HTLC:
4594         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
4595         // 1st HTLC:
4596         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
4597         let route = nodes[1].router.get_route(&nodes[5].node.get_our_node_id(), None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV).unwrap();
4598         // 2nd HTLC:
4599         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
4600         // 3rd HTLC:
4601         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
4602         // 4th HTLC:
4603         let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4604         // 5th HTLC:
4605         let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4606         let route = nodes[1].router.get_route(&nodes[5].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
4607         // 6th HTLC:
4608         send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
4609         // 7th HTLC:
4610         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
4611
4612         // 8th HTLC:
4613         let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4614         // 9th HTLC:
4615         let route = nodes[1].router.get_route(&nodes[5].node.get_our_node_id(), None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV).unwrap();
4616         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
4617
4618         // 10th HTLC:
4619         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
4620         // 11th HTLC:
4621         let route = nodes[1].router.get_route(&nodes[5].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
4622         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
4623
4624         // Double-check that six of the new HTLC were added
4625         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
4626         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
4627         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
4628         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
4629
4630         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
4631         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
4632         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1));
4633         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3));
4634         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5));
4635         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6));
4636         check_added_monitors!(nodes[4], 0);
4637         expect_pending_htlcs_forwardable!(nodes[4]);
4638         check_added_monitors!(nodes[4], 1);
4639
4640         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
4641         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
4642         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
4643         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
4644         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
4645         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
4646
4647         // Fail 3rd below-dust and 7th above-dust HTLCs
4648         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2));
4649         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4));
4650         check_added_monitors!(nodes[5], 0);
4651         expect_pending_htlcs_forwardable!(nodes[5]);
4652         check_added_monitors!(nodes[5], 1);
4653
4654         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
4655         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
4656         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
4657         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
4658
4659         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
4660
4661         expect_pending_htlcs_forwardable!(nodes[3]);
4662         check_added_monitors!(nodes[3], 1);
4663         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
4664         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
4665         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
4666         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
4667         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
4668         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
4669         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
4670         if deliver_last_raa {
4671                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
4672         } else {
4673                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
4674         }
4675
4676         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
4677         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
4678         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
4679         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
4680         //
4681         // We now broadcast the latest commitment transaction, which *should* result in failures for
4682         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
4683         // the non-broadcast above-dust HTLCs.
4684         //
4685         // Alternatively, we may broadcast the previous commitment transaction, which should only
4686         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
4687         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
4688
4689         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4690         if announce_latest {
4691                 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![ds_last_commitment_tx[0].clone()]}, 1);
4692         } else {
4693                 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![ds_prev_commitment_tx[0].clone()]}, 1);
4694         }
4695         connect_blocks(&nodes[2].block_notifier, ANTI_REORG_DELAY - 1, 1, true,  header.bitcoin_hash());
4696         check_closed_broadcast!(nodes[2], false);
4697         expect_pending_htlcs_forwardable!(nodes[2]);
4698         check_added_monitors!(nodes[2], 3);
4699
4700         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
4701         assert_eq!(cs_msgs.len(), 2);
4702         let mut a_done = false;
4703         for msg in cs_msgs {
4704                 match msg {
4705                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
4706                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
4707                                 // should be failed-backwards here.
4708                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
4709                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
4710                                         for htlc in &updates.update_fail_htlcs {
4711                                                 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 });
4712                                         }
4713                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
4714                                         assert!(!a_done);
4715                                         a_done = true;
4716                                         &nodes[0]
4717                                 } else {
4718                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
4719                                         for htlc in &updates.update_fail_htlcs {
4720                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
4721                                         }
4722                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
4723                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
4724                                         &nodes[1]
4725                                 };
4726                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
4727                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
4728                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
4729                                 if announce_latest {
4730                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
4731                                         if *node_id == nodes[0].node.get_our_node_id() {
4732                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
4733                                         }
4734                                 }
4735                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
4736                         },
4737                         _ => panic!("Unexpected event"),
4738                 }
4739         }
4740
4741         let as_events = nodes[0].node.get_and_clear_pending_events();
4742         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
4743         let mut as_failds = HashSet::new();
4744         for event in as_events.iter() {
4745                 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
4746                         assert!(as_failds.insert(*payment_hash));
4747                         if *payment_hash != payment_hash_2 {
4748                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
4749                         } else {
4750                                 assert!(!rejected_by_dest);
4751                         }
4752                 } else { panic!("Unexpected event"); }
4753         }
4754         assert!(as_failds.contains(&payment_hash_1));
4755         assert!(as_failds.contains(&payment_hash_2));
4756         if announce_latest {
4757                 assert!(as_failds.contains(&payment_hash_3));
4758                 assert!(as_failds.contains(&payment_hash_5));
4759         }
4760         assert!(as_failds.contains(&payment_hash_6));
4761
4762         let bs_events = nodes[1].node.get_and_clear_pending_events();
4763         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
4764         let mut bs_failds = HashSet::new();
4765         for event in bs_events.iter() {
4766                 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
4767                         assert!(bs_failds.insert(*payment_hash));
4768                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
4769                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
4770                         } else {
4771                                 assert!(!rejected_by_dest);
4772                         }
4773                 } else { panic!("Unexpected event"); }
4774         }
4775         assert!(bs_failds.contains(&payment_hash_1));
4776         assert!(bs_failds.contains(&payment_hash_2));
4777         if announce_latest {
4778                 assert!(bs_failds.contains(&payment_hash_4));
4779         }
4780         assert!(bs_failds.contains(&payment_hash_5));
4781
4782         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
4783         // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
4784         // to unknown-preimage-etc, B should have gotten 2. Thus, in the
4785         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
4786         // PaymentFailureNetworkUpdates.
4787         let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4788         assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
4789         let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4790         assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
4791         for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
4792                 match event {
4793                         &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
4794                         _ => panic!("Unexpected event"),
4795                 }
4796         }
4797 }
4798
4799 #[test]
4800 fn test_fail_backwards_latest_remote_announce_a() {
4801         do_test_fail_backwards_unrevoked_remote_announce(false, true);
4802 }
4803
4804 #[test]
4805 fn test_fail_backwards_latest_remote_announce_b() {
4806         do_test_fail_backwards_unrevoked_remote_announce(true, true);
4807 }
4808
4809 #[test]
4810 fn test_fail_backwards_previous_remote_announce() {
4811         do_test_fail_backwards_unrevoked_remote_announce(false, false);
4812         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
4813         // tested for in test_commitment_revoked_fail_backward_exhaustive()
4814 }
4815
4816 #[test]
4817 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
4818         let chanmon_cfgs = create_chanmon_cfgs(2);
4819         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4820         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4821         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4822
4823         // Create some initial channels
4824         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4825
4826         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
4827         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4828         assert_eq!(local_txn[0].input.len(), 1);
4829         check_spends!(local_txn[0], chan_1.3);
4830
4831         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
4832         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4833         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![local_txn[0].clone()] }, 200);
4834         check_closed_broadcast!(nodes[0], false);
4835         check_added_monitors!(nodes[0], 1);
4836
4837         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4838         assert_eq!(node_txn[0].input.len(), 1);
4839         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4840         check_spends!(node_txn[0], local_txn[0]);
4841
4842         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
4843         let spend_txn = check_spendable_outputs!(nodes[0], 1);
4844         assert_eq!(spend_txn.len(), 8);
4845         assert_eq!(spend_txn[0], spend_txn[2]);
4846         assert_eq!(spend_txn[0], spend_txn[4]);
4847         assert_eq!(spend_txn[0], spend_txn[6]);
4848         assert_eq!(spend_txn[1], spend_txn[3]);
4849         assert_eq!(spend_txn[1], spend_txn[5]);
4850         assert_eq!(spend_txn[1], spend_txn[7]);
4851         check_spends!(spend_txn[0], local_txn[0]);
4852         check_spends!(spend_txn[1], node_txn[0]);
4853 }
4854
4855 #[test]
4856 fn test_static_output_closing_tx() {
4857         let chanmon_cfgs = create_chanmon_cfgs(2);
4858         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4859         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4860         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4861
4862         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4863
4864         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
4865         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
4866
4867         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4868         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
4869         let spend_txn = check_spendable_outputs!(nodes[0], 2);
4870         assert_eq!(spend_txn.len(), 1);
4871         check_spends!(spend_txn[0], closing_tx);
4872
4873         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
4874         let spend_txn = check_spendable_outputs!(nodes[1], 2);
4875         assert_eq!(spend_txn.len(), 1);
4876         check_spends!(spend_txn[0], closing_tx);
4877 }
4878
4879 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
4880         let chanmon_cfgs = create_chanmon_cfgs(2);
4881         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4882         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4883         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4884         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4885
4886         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
4887
4888         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
4889         // present in B's local commitment transaction, but none of A's commitment transactions.
4890         assert!(nodes[1].node.claim_funds(our_payment_preimage, if use_dust { 50_000 } else { 3_000_000 }));
4891         check_added_monitors!(nodes[1], 1);
4892
4893         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4894         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
4895         let events = nodes[0].node.get_and_clear_pending_events();
4896         assert_eq!(events.len(), 1);
4897         match events[0] {
4898                 Event::PaymentSent { payment_preimage } => {
4899                         assert_eq!(payment_preimage, our_payment_preimage);
4900                 },
4901                 _ => panic!("Unexpected event"),
4902         }
4903
4904         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
4905         check_added_monitors!(nodes[0], 1);
4906         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4907         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
4908         check_added_monitors!(nodes[1], 1);
4909
4910         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4911         for i in 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + CHAN_CONFIRM_DEPTH + 1 {
4912                 nodes[1].block_notifier.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
4913                 header.prev_blockhash = header.bitcoin_hash();
4914         }
4915         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
4916         check_closed_broadcast!(nodes[1], false);
4917         check_added_monitors!(nodes[1], 1);
4918 }
4919
4920 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
4921         let chanmon_cfgs = create_chanmon_cfgs(2);
4922         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4923         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4924         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4925         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4926
4927         let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), if use_dust { 50000 } else { 3000000 }, TEST_FINAL_CLTV).unwrap();
4928         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
4929         nodes[0].node.send_payment(route, payment_hash).unwrap();
4930         check_added_monitors!(nodes[0], 1);
4931
4932         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4933
4934         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
4935         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
4936         // to "time out" the HTLC.
4937
4938         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4939
4940         for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
4941                 nodes[0].block_notifier.block_connected(&Block { header, txdata: Vec::new()}, i);
4942                 header.prev_blockhash = header.bitcoin_hash();
4943         }
4944         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
4945         check_closed_broadcast!(nodes[0], false);
4946         check_added_monitors!(nodes[0], 1);
4947 }
4948
4949 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
4950         let chanmon_cfgs = create_chanmon_cfgs(3);
4951         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4952         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4953         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4954         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4955
4956         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
4957         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
4958         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
4959         // actually revoked.
4960         let htlc_value = if use_dust { 50000 } else { 3000000 };
4961         let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
4962         assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash));
4963         expect_pending_htlcs_forwardable!(nodes[1]);
4964         check_added_monitors!(nodes[1], 1);
4965
4966         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4967         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
4968         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
4969         check_added_monitors!(nodes[0], 1);
4970         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4971         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
4972         check_added_monitors!(nodes[1], 1);
4973         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
4974         check_added_monitors!(nodes[1], 1);
4975         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4976
4977         if check_revoke_no_close {
4978                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4979                 check_added_monitors!(nodes[0], 1);
4980         }
4981
4982         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4983         for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
4984                 nodes[0].block_notifier.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
4985                 header.prev_blockhash = header.bitcoin_hash();
4986         }
4987         if !check_revoke_no_close {
4988                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
4989                 check_closed_broadcast!(nodes[0], false);
4990                 check_added_monitors!(nodes[0], 1);
4991         } else {
4992                 let events = nodes[0].node.get_and_clear_pending_events();
4993                 assert_eq!(events.len(), 1);
4994                 match events[0] {
4995                         Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
4996                                 assert_eq!(payment_hash, our_payment_hash);
4997                                 assert!(rejected_by_dest);
4998                         },
4999                         _ => panic!("Unexpected event"),
5000                 }
5001         }
5002 }
5003
5004 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5005 // There are only a few cases to test here:
5006 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5007 //    broadcastable commitment transactions result in channel closure,
5008 //  * its included in an unrevoked-but-previous remote commitment transaction,
5009 //  * its included in the latest remote or local commitment transactions.
5010 // We test each of the three possible commitment transactions individually and use both dust and
5011 // non-dust HTLCs.
5012 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5013 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5014 // tested for at least one of the cases in other tests.
5015 #[test]
5016 fn htlc_claim_single_commitment_only_a() {
5017         do_htlc_claim_local_commitment_only(true);
5018         do_htlc_claim_local_commitment_only(false);
5019
5020         do_htlc_claim_current_remote_commitment_only(true);
5021         do_htlc_claim_current_remote_commitment_only(false);
5022 }
5023
5024 #[test]
5025 fn htlc_claim_single_commitment_only_b() {
5026         do_htlc_claim_previous_remote_commitment_only(true, false);
5027         do_htlc_claim_previous_remote_commitment_only(false, false);
5028         do_htlc_claim_previous_remote_commitment_only(true, true);
5029         do_htlc_claim_previous_remote_commitment_only(false, true);
5030 }
5031
5032 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>)
5033         where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
5034                                 F2: FnMut(),
5035 {
5036         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);
5037 }
5038
5039 // test_case
5040 // 0: node1 fails backward
5041 // 1: final node fails backward
5042 // 2: payment completed but the user rejects the payment
5043 // 3: final node fails backward (but tamper onion payloads from node0)
5044 // 100: trigger error in the intermediate node and tamper returning fail_htlc
5045 // 200: trigger error in the final node and tamper returning fail_htlc
5046 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>)
5047         where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
5048                                 F2: for <'a> FnMut(&'a mut msgs::UpdateFailHTLC),
5049                                 F3: FnMut(),
5050 {
5051
5052         // reset block height
5053         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5054         for ix in 0..nodes.len() {
5055                 nodes[ix].block_notifier.block_connected_checked(&header, 1, &[], &[]);
5056         }
5057
5058         macro_rules! expect_event {
5059                 ($node: expr, $event_type: path) => {{
5060                         let events = $node.node.get_and_clear_pending_events();
5061                         assert_eq!(events.len(), 1);
5062                         match events[0] {
5063                                 $event_type { .. } => {},
5064                                 _ => panic!("Unexpected event"),
5065                         }
5066                 }}
5067         }
5068
5069         macro_rules! expect_htlc_forward {
5070                 ($node: expr) => {{
5071                         expect_event!($node, Event::PendingHTLCsForwardable);
5072                         $node.node.process_pending_htlc_forwards();
5073                 }}
5074         }
5075
5076         // 0 ~~> 2 send payment
5077         nodes[0].node.send_payment(route.clone(), payment_hash.clone()).unwrap();
5078         check_added_monitors!(nodes[0], 1);
5079         let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5080         // temper update_add (0 => 1)
5081         let mut update_add_0 = update_0.update_add_htlcs[0].clone();
5082         if test_case == 0 || test_case == 3 || test_case == 100 {
5083                 callback_msg(&mut update_add_0);
5084                 callback_node();
5085         }
5086         // 0 => 1 update_add & CS
5087         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_0);
5088         commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
5089
5090         let update_1_0 = match test_case {
5091                 0|100 => { // intermediate node failure; fail backward to 0
5092                         let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5093                         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));
5094                         update_1_0
5095                 },
5096                 1|2|3|200 => { // final node failure; forwarding to 2
5097                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5098                         // forwarding on 1
5099                         if test_case != 200 {
5100                                 callback_node();
5101                         }
5102                         expect_htlc_forward!(&nodes[1]);
5103
5104                         let update_1 = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
5105                         check_added_monitors!(&nodes[1], 1);
5106                         assert_eq!(update_1.update_add_htlcs.len(), 1);
5107                         // tamper update_add (1 => 2)
5108                         let mut update_add_1 = update_1.update_add_htlcs[0].clone();
5109                         if test_case != 3 && test_case != 200 {
5110                                 callback_msg(&mut update_add_1);
5111                         }
5112
5113                         // 1 => 2
5114                         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_1);
5115                         commitment_signed_dance!(nodes[2], nodes[1], update_1.commitment_signed, false, true);
5116
5117                         if test_case == 2 || test_case == 200 {
5118                                 expect_htlc_forward!(&nodes[2]);
5119                                 expect_event!(&nodes[2], Event::PaymentReceived);
5120                                 callback_node();
5121                                 expect_pending_htlcs_forwardable!(nodes[2]);
5122                         }
5123
5124                         let update_2_1 = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5125                         if test_case == 2 || test_case == 200 {
5126                                 check_added_monitors!(&nodes[2], 1);
5127                         }
5128                         assert!(update_2_1.update_fail_htlcs.len() == 1);
5129
5130                         let mut fail_msg = update_2_1.update_fail_htlcs[0].clone();
5131                         if test_case == 200 {
5132                                 callback_fail(&mut fail_msg);
5133                         }
5134
5135                         // 2 => 1
5136                         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_msg);
5137                         commitment_signed_dance!(nodes[1], nodes[2], update_2_1.commitment_signed, true);
5138
5139                         // backward fail on 1
5140                         let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5141                         assert!(update_1_0.update_fail_htlcs.len() == 1);
5142                         update_1_0
5143                 },
5144                 _ => unreachable!(),
5145         };
5146
5147         // 1 => 0 commitment_signed_dance
5148         if update_1_0.update_fail_htlcs.len() > 0 {
5149                 let mut fail_msg = update_1_0.update_fail_htlcs[0].clone();
5150                 if test_case == 100 {
5151                         callback_fail(&mut fail_msg);
5152                 }
5153                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
5154         } else {
5155                 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_1_0.update_fail_malformed_htlcs[0]);
5156         };
5157
5158         commitment_signed_dance!(nodes[0], nodes[1], update_1_0.commitment_signed, false, true);
5159
5160         let events = nodes[0].node.get_and_clear_pending_events();
5161         assert_eq!(events.len(), 1);
5162         if let &Event::PaymentFailed { payment_hash:_, ref rejected_by_dest, ref error_code } = &events[0] {
5163                 assert_eq!(*rejected_by_dest, !expected_retryable);
5164                 assert_eq!(*error_code, expected_error_code);
5165         } else {
5166                 panic!("Uexpected event");
5167         }
5168
5169         let events = nodes[0].node.get_and_clear_pending_msg_events();
5170         if expected_channel_update.is_some() {
5171                 assert_eq!(events.len(), 1);
5172                 match events[0] {
5173                         MessageSendEvent::PaymentFailureNetworkUpdate { ref update } => {
5174                                 match update {
5175                                         &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {
5176                                                 if let HTLCFailChannelUpdate::ChannelUpdateMessage { .. } = expected_channel_update.unwrap() {} else {
5177                                                         panic!("channel_update not found!");
5178                                                 }
5179                                         },
5180                                         &HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, ref is_permanent } => {
5181                                                 if let HTLCFailChannelUpdate::ChannelClosed { short_channel_id: ref expected_short_channel_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
5182                                                         assert!(*short_channel_id == *expected_short_channel_id);
5183                                                         assert!(*is_permanent == *expected_is_permanent);
5184                                                 } else {
5185                                                         panic!("Unexpected message event");
5186                                                 }
5187                                         },
5188                                         &HTLCFailChannelUpdate::NodeFailure { ref node_id, ref is_permanent } => {
5189                                                 if let HTLCFailChannelUpdate::NodeFailure { node_id: ref expected_node_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
5190                                                         assert!(*node_id == *expected_node_id);
5191                                                         assert!(*is_permanent == *expected_is_permanent);
5192                                                 } else {
5193                                                         panic!("Unexpected message event");
5194                                                 }
5195                                         },
5196                                 }
5197                         },
5198                         _ => panic!("Unexpected message event"),
5199                 }
5200         } else {
5201                 assert_eq!(events.len(), 0);
5202         }
5203 }
5204
5205 impl msgs::ChannelUpdate {
5206         fn dummy() -> msgs::ChannelUpdate {
5207                 use secp256k1::ffi::Signature as FFISignature;
5208                 use secp256k1::Signature;
5209                 msgs::ChannelUpdate {
5210                         signature: Signature::from(FFISignature::new()),
5211                         contents: msgs::UnsignedChannelUpdate {
5212                                 chain_hash: Sha256dHash::hash(&vec![0u8][..]),
5213                                 short_channel_id: 0,
5214                                 timestamp: 0,
5215                                 flags: 0,
5216                                 cltv_expiry_delta: 0,
5217                                 htlc_minimum_msat: 0,
5218                                 fee_base_msat: 0,
5219                                 fee_proportional_millionths: 0,
5220                                 excess_data: vec![],
5221                         }
5222                 }
5223         }
5224 }
5225
5226 struct BogusOnionHopData {
5227         data: Vec<u8>
5228 }
5229 impl BogusOnionHopData {
5230         fn new(orig: msgs::OnionHopData) -> Self {
5231                 Self { data: orig.encode() }
5232         }
5233 }
5234 impl Writeable for BogusOnionHopData {
5235         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
5236                 writer.write_all(&self.data[..])
5237         }
5238 }
5239
5240 #[test]
5241 fn test_onion_failure() {
5242         use ln::msgs::ChannelUpdate;
5243         use ln::channelmanager::CLTV_FAR_FAR_AWAY;
5244         use secp256k1;
5245
5246         const BADONION: u16 = 0x8000;
5247         const PERM: u16 = 0x4000;
5248         const NODE: u16 = 0x2000;
5249         const UPDATE: u16 = 0x1000;
5250
5251         let chanmon_cfgs = create_chanmon_cfgs(3);
5252         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5253         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5254         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5255         for node in nodes.iter() {
5256                 *node.keys_manager.override_session_priv.lock().unwrap() = Some(SecretKey::from_slice(&[3; 32]).unwrap());
5257         }
5258         let channels = [create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported()), create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported())];
5259         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5260         let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV).unwrap();
5261         // positve case
5262         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 40000, 40_000);
5263
5264         // intermediate node failure
5265         run_onion_failure_test("invalid_realm", 0, &nodes, &route, &payment_hash, |msg| {
5266                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5267                 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5268                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5269                 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
5270                 let mut new_payloads = Vec::new();
5271                 for payload in onion_payloads.drain(..) {
5272                         new_payloads.push(BogusOnionHopData::new(payload));
5273                 }
5274                 // break the first (non-final) hop payload by swapping the realm (0) byte for a byte
5275                 // describing a length-1 TLV payload, which is obviously bogus.
5276                 new_payloads[0].data[0] = 1;
5277                 msg.onion_routing_packet = onion_utils::construct_onion_packet_bogus_hopdata(new_payloads, onion_keys, [0; 32], &payment_hash);
5278         }, ||{}, 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
5279
5280         // final node failure
5281         run_onion_failure_test("invalid_realm", 3, &nodes, &route, &payment_hash, |msg| {
5282                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5283                 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5284                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5285                 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
5286                 let mut new_payloads = Vec::new();
5287                 for payload in onion_payloads.drain(..) {
5288                         new_payloads.push(BogusOnionHopData::new(payload));
5289                 }
5290                 // break the last-hop payload by swapping the realm (0) byte for a byte describing a
5291                 // length-1 TLV payload, which is obviously bogus.
5292                 new_payloads[1].data[0] = 1;
5293                 msg.onion_routing_packet = onion_utils::construct_onion_packet_bogus_hopdata(new_payloads, onion_keys, [0; 32], &payment_hash);
5294         }, ||{}, false, Some(PERM|22), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
5295
5296         // the following three with run_onion_failure_test_with_fail_intercept() test only the origin node
5297         // receiving simulated fail messages
5298         // intermediate node failure
5299         run_onion_failure_test_with_fail_intercept("temporary_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
5300                 // trigger error
5301                 msg.amount_msat -= 1;
5302         }, |msg| {
5303                 // and tamper returning error message
5304                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5305                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5306                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], NODE|2, &[0;0]);
5307         }, ||{}, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: false}));
5308
5309         // final node failure
5310         run_onion_failure_test_with_fail_intercept("temporary_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
5311                 // and tamper returning error message
5312                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5313                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5314                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], NODE|2, &[0;0]);
5315         }, ||{
5316                 nodes[2].node.fail_htlc_backwards(&payment_hash);
5317         }, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: false}));
5318
5319         // intermediate node failure
5320         run_onion_failure_test_with_fail_intercept("permanent_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
5321                 msg.amount_msat -= 1;
5322         }, |msg| {
5323                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5324                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5325                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|2, &[0;0]);
5326         }, ||{}, true, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: true}));
5327
5328         // final node failure
5329         run_onion_failure_test_with_fail_intercept("permanent_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
5330                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5331                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5332                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|2, &[0;0]);
5333         }, ||{
5334                 nodes[2].node.fail_htlc_backwards(&payment_hash);
5335         }, false, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: true}));
5336
5337         // intermediate node failure
5338         run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
5339                 msg.amount_msat -= 1;
5340         }, |msg| {
5341                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5342                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5343                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|3, &[0;0]);
5344         }, ||{
5345                 nodes[2].node.fail_htlc_backwards(&payment_hash);
5346         }, true, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: true}));
5347
5348         // final node failure
5349         run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
5350                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5351                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5352                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|3, &[0;0]);
5353         }, ||{
5354                 nodes[2].node.fail_htlc_backwards(&payment_hash);
5355         }, false, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: true}));
5356
5357         run_onion_failure_test("invalid_onion_version", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.version = 1; }, ||{}, true,
5358                 Some(BADONION|PERM|4), None);
5359
5360         run_onion_failure_test("invalid_onion_hmac", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.hmac = [3; 32]; }, ||{}, true,
5361                 Some(BADONION|PERM|5), None);
5362
5363         run_onion_failure_test("invalid_onion_key", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.public_key = Err(secp256k1::Error::InvalidPublicKey);}, ||{}, true,
5364                 Some(BADONION|PERM|6), None);
5365
5366         run_onion_failure_test_with_fail_intercept("temporary_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
5367                 msg.amount_msat -= 1;
5368         }, |msg| {
5369                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5370                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5371                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], UPDATE|7, &ChannelUpdate::dummy().encode_with_len()[..]);
5372         }, ||{}, true, Some(UPDATE|7), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5373
5374         run_onion_failure_test_with_fail_intercept("permanent_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
5375                 msg.amount_msat -= 1;
5376         }, |msg| {
5377                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5378                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5379                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|8, &[0;0]);
5380                 // short_channel_id from the processing node
5381         }, ||{}, true, Some(PERM|8), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
5382
5383         run_onion_failure_test_with_fail_intercept("required_channel_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
5384                 msg.amount_msat -= 1;
5385         }, |msg| {
5386                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5387                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5388                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|9, &[0;0]);
5389                 // short_channel_id from the processing node
5390         }, ||{}, true, Some(PERM|9), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
5391
5392         let mut bogus_route = route.clone();
5393         bogus_route.hops[1].short_channel_id -= 1;
5394         run_onion_failure_test("unknown_next_peer", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(PERM|10),
5395           Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: bogus_route.hops[1].short_channel_id, is_permanent:true}));
5396
5397         let amt_to_forward = nodes[1].node.channel_state.lock().unwrap().by_id.get(&channels[1].2).unwrap().get_their_htlc_minimum_msat() - 1;
5398         let mut bogus_route = route.clone();
5399         let route_len = bogus_route.hops.len();
5400         bogus_route.hops[route_len-1].fee_msat = amt_to_forward;
5401         run_onion_failure_test("amount_below_minimum", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(UPDATE|11), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5402
5403         //TODO: with new config API, we will be able to generate both valid and
5404         //invalid channel_update cases.
5405         run_onion_failure_test("fee_insufficient", 0, &nodes, &route, &payment_hash, |msg| {
5406                 msg.amount_msat -= 1;
5407         }, || {}, true, Some(UPDATE|12), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
5408
5409         run_onion_failure_test("incorrect_cltv_expiry", 0, &nodes, &route, &payment_hash, |msg| {
5410                 // need to violate: cltv_expiry - cltv_expiry_delta >= outgoing_cltv_value
5411                 msg.cltv_expiry -= 1;
5412         }, || {}, true, Some(UPDATE|13), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
5413
5414         run_onion_failure_test("expiry_too_soon", 0, &nodes, &route, &payment_hash, |msg| {
5415                 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
5416                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5417
5418                 nodes[1].block_notifier.block_connected_checked(&header, height, &[], &[]);
5419         }, ||{}, true, Some(UPDATE|14), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5420
5421         run_onion_failure_test("unknown_payment_hash", 2, &nodes, &route, &payment_hash, |_| {}, || {
5422                 nodes[2].node.fail_htlc_backwards(&payment_hash);
5423         }, false, Some(PERM|15), None);
5424
5425         run_onion_failure_test("final_expiry_too_soon", 1, &nodes, &route, &payment_hash, |msg| {
5426                 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
5427                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5428
5429                 nodes[2].block_notifier.block_connected_checked(&header, height, &[], &[]);
5430         }, || {}, true, Some(17), None);
5431
5432         run_onion_failure_test("final_incorrect_cltv_expiry", 1, &nodes, &route, &payment_hash, |_| {}, || {
5433                 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().forward_htlcs.iter_mut() {
5434                         for f in pending_forwards.iter_mut() {
5435                                 match f {
5436                                         &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
5437                                                 forward_info.outgoing_cltv_value += 1,
5438                                         _ => {},
5439                                 }
5440                         }
5441                 }
5442         }, true, Some(18), None);
5443
5444         run_onion_failure_test("final_incorrect_htlc_amount", 1, &nodes, &route, &payment_hash, |_| {}, || {
5445                 // violate amt_to_forward > msg.amount_msat
5446                 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().forward_htlcs.iter_mut() {
5447                         for f in pending_forwards.iter_mut() {
5448                                 match f {
5449                                         &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
5450                                                 forward_info.amt_to_forward -= 1,
5451                                         _ => {},
5452                                 }
5453                         }
5454                 }
5455         }, true, Some(19), None);
5456
5457         run_onion_failure_test("channel_disabled", 0, &nodes, &route, &payment_hash, |_| {}, || {
5458                 // disconnect event to the channel between nodes[1] ~ nodes[2]
5459                 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
5460                 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5461         }, true, Some(UPDATE|20), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5462         reconnect_nodes(&nodes[1], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5463
5464         run_onion_failure_test("expiry_too_far", 0, &nodes, &route, &payment_hash, |msg| {
5465                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5466                 let mut route = route.clone();
5467                 let height = 1;
5468                 route.hops[1].cltv_expiry_delta += CLTV_FAR_FAR_AWAY + route.hops[0].cltv_expiry_delta + 1;
5469                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5470                 let (onion_payloads, _, htlc_cltv) = onion_utils::build_onion_payloads(&route, height).unwrap();
5471                 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
5472                 msg.cltv_expiry = htlc_cltv;
5473                 msg.onion_routing_packet = onion_packet;
5474         }, ||{}, true, Some(21), None);
5475 }
5476
5477 #[test]
5478 #[should_panic]
5479 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5480         let chanmon_cfgs = create_chanmon_cfgs(2);
5481         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5482         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5483         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5484         //Force duplicate channel ids
5485         for node in nodes.iter() {
5486                 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5487         }
5488
5489         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5490         let channel_value_satoshis=10000;
5491         let push_msat=10001;
5492         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5493         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5494         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::supported(), &node0_to_1_send_open_channel);
5495
5496         //Create a second channel with a channel_id collision
5497         assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5498 }
5499
5500 #[test]
5501 fn bolt2_open_channel_sending_node_checks_part2() {
5502         let chanmon_cfgs = create_chanmon_cfgs(2);
5503         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5504         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5505         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5506
5507         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5508         let channel_value_satoshis=2^24;
5509         let push_msat=10001;
5510         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5511
5512         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5513         let channel_value_satoshis=10000;
5514         // Test when push_msat is equal to 1000 * funding_satoshis.
5515         let push_msat=1000*channel_value_satoshis+1;
5516         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5517
5518         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5519         let channel_value_satoshis=10000;
5520         let push_msat=10001;
5521         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
5522         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5523         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5524
5525         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5526         // 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
5527         assert!(node0_to_1_send_open_channel.channel_flags<=1);
5528
5529         // 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.
5530         assert!(BREAKDOWN_TIMEOUT>0);
5531         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5532
5533         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5534         let chain_hash=genesis_block(Network::Testnet).header.bitcoin_hash();
5535         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5536
5537         // 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.
5538         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5539         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5540         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5541         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_basepoint.serialize()).is_ok());
5542         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5543 }
5544
5545 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
5546 // 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.
5547 //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.
5548
5549 #[test]
5550 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
5551         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
5552         let chanmon_cfgs = create_chanmon_cfgs(2);
5553         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5554         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5555         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5556         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::supported(), InitFeatures::supported());
5557         let mut route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
5558         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5559
5560         route.hops[0].fee_msat = 100;
5561
5562         let err = nodes[0].node.send_payment(route, our_payment_hash);
5563
5564         if let Err(APIError::ChannelUnavailable{err}) = err {
5565                 assert_eq!(err, "Cannot send less than their minimum HTLC value");
5566         } else {
5567                 assert!(false);
5568         }
5569         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5570         nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
5571 }
5572
5573 #[test]
5574 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
5575         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
5576         let chanmon_cfgs = create_chanmon_cfgs(2);
5577         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5578         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5579         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5580         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::supported(), InitFeatures::supported());
5581         let mut route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
5582         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5583
5584         route.hops[0].fee_msat = 0;
5585
5586         let err = nodes[0].node.send_payment(route, our_payment_hash);
5587
5588         if let Err(APIError::ChannelUnavailable{err}) = err {
5589                 assert_eq!(err, "Cannot send 0-msat HTLC");
5590         } else {
5591                 assert!(false);
5592         }
5593         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5594         nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
5595 }
5596
5597 #[test]
5598 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
5599         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
5600         let chanmon_cfgs = create_chanmon_cfgs(2);
5601         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5602         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5603         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5604         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::supported(), InitFeatures::supported());
5605         let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
5606         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5607
5608         nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5609         check_added_monitors!(nodes[0], 1);
5610         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5611         updates.update_add_htlcs[0].amount_msat = 0;
5612
5613         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5614         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
5615         check_closed_broadcast!(nodes[1], true).unwrap();
5616         check_added_monitors!(nodes[1], 1);
5617 }
5618
5619 #[test]
5620 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
5621         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
5622         //It is enforced when constructing a route.
5623         let chanmon_cfgs = create_chanmon_cfgs(2);
5624         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5625         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5626         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5627         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 0, InitFeatures::supported(), InitFeatures::supported());
5628         let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000000, 500000001).unwrap();
5629         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5630
5631         let err = nodes[0].node.send_payment(route, our_payment_hash);
5632
5633         if let Err(APIError::RouteError{err}) = err {
5634                 assert_eq!(err, "Channel CLTV overflowed?!");
5635         } else {
5636                 assert!(false);
5637         }
5638 }
5639
5640 #[test]
5641 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
5642         //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.
5643         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
5644         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
5645         let chanmon_cfgs = create_chanmon_cfgs(2);
5646         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5647         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5648         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5649         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::supported(), InitFeatures::supported());
5650         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().their_max_accepted_htlcs as u64;
5651
5652         for i in 0..max_accepted_htlcs {
5653                 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
5654                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5655                 let payment_event = {
5656                         nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5657                         check_added_monitors!(nodes[0], 1);
5658
5659                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5660                         assert_eq!(events.len(), 1);
5661                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
5662                                 assert_eq!(htlcs[0].htlc_id, i);
5663                         } else {
5664                                 assert!(false);
5665                         }
5666                         SendEvent::from_event(events.remove(0))
5667                 };
5668                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5669                 check_added_monitors!(nodes[1], 0);
5670                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5671
5672                 expect_pending_htlcs_forwardable!(nodes[1]);
5673                 expect_payment_received!(nodes[1], our_payment_hash, 100000);
5674         }
5675         let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
5676         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5677         let err = nodes[0].node.send_payment(route, our_payment_hash);
5678
5679         if let Err(APIError::ChannelUnavailable{err}) = err {
5680                 assert_eq!(err, "Cannot push more than their max accepted HTLCs");
5681         } else {
5682                 assert!(false);
5683         }
5684         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5685         nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
5686 }
5687
5688 #[test]
5689 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
5690         //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.
5691         let chanmon_cfgs = create_chanmon_cfgs(2);
5692         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5693         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5694         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5695         let channel_value = 100000;
5696         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::supported(), InitFeatures::supported());
5697         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).their_max_htlc_value_in_flight_msat;
5698
5699         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight, max_in_flight);
5700
5701         let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], max_in_flight+1, TEST_FINAL_CLTV).unwrap();
5702         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5703         let err = nodes[0].node.send_payment(route, our_payment_hash);
5704
5705         if let Err(APIError::ChannelUnavailable{err}) = err {
5706                 assert_eq!(err, "Cannot send value that would put us over the max HTLC value in flight our peer will accept");
5707         } else {
5708                 assert!(false);
5709         }
5710         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5711         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);
5712
5713         send_payment(&nodes[0], &[&nodes[1]], max_in_flight, max_in_flight);
5714 }
5715
5716 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
5717 #[test]
5718 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
5719         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
5720         let chanmon_cfgs = create_chanmon_cfgs(2);
5721         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5722         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5723         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5724         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::supported(), InitFeatures::supported());
5725         let htlc_minimum_msat: u64;
5726         {
5727                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
5728                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
5729                 htlc_minimum_msat = channel.get_our_htlc_minimum_msat();
5730         }
5731         let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], htlc_minimum_msat, TEST_FINAL_CLTV).unwrap();
5732         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5733         nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5734         check_added_monitors!(nodes[0], 1);
5735         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5736         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
5737         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5738         assert!(nodes[1].node.list_channels().is_empty());
5739         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
5740         assert_eq!(err_msg.data, "Remote side tried to send less than our minimum HTLC value");
5741         check_added_monitors!(nodes[1], 1);
5742 }
5743
5744 #[test]
5745 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
5746         //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
5747         let chanmon_cfgs = create_chanmon_cfgs(2);
5748         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5749         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5750         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5751         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::supported(), InitFeatures::supported());
5752
5753         let their_channel_reserve = get_channel_value_stat!(nodes[0], chan.2).channel_reserve_msat;
5754
5755         let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 5000000-their_channel_reserve, TEST_FINAL_CLTV).unwrap();
5756         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5757         nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5758         check_added_monitors!(nodes[0], 1);
5759         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5760
5761         updates.update_add_htlcs[0].amount_msat = 5000000-their_channel_reserve+1;
5762         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5763
5764         assert!(nodes[1].node.list_channels().is_empty());
5765         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
5766         assert_eq!(err_msg.data, "Remote HTLC add would put them over their reserve value");
5767         check_added_monitors!(nodes[1], 1);
5768 }
5769
5770 #[test]
5771 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
5772         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
5773         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
5774         let chanmon_cfgs = create_chanmon_cfgs(2);
5775         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5776         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5777         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5778         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::supported(), InitFeatures::supported());
5779         let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 3999999, TEST_FINAL_CLTV).unwrap();
5780         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5781
5782         let session_priv = SecretKey::from_slice(&{
5783                 let mut session_key = [0; 32];
5784                 let mut rng = thread_rng();
5785                 rng.fill_bytes(&mut session_key);
5786                 session_key
5787         }).expect("RNG is bad!");
5788
5789         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5790         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route, &session_priv).unwrap();
5791         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
5792         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
5793
5794         let mut msg = msgs::UpdateAddHTLC {
5795                 channel_id: chan.2,
5796                 htlc_id: 0,
5797                 amount_msat: 1000,
5798                 payment_hash: our_payment_hash,
5799                 cltv_expiry: htlc_cltv,
5800                 onion_routing_packet: onion_packet.clone(),
5801         };
5802
5803         for i in 0..super::channel::OUR_MAX_HTLCS {
5804                 msg.htlc_id = i as u64;
5805                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
5806         }
5807         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
5808         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
5809
5810         assert!(nodes[1].node.list_channels().is_empty());
5811         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
5812         assert_eq!(err_msg.data, "Remote tried to push more than our max accepted HTLCs");
5813         check_added_monitors!(nodes[1], 1);
5814 }
5815
5816 #[test]
5817 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
5818         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
5819         let chanmon_cfgs = create_chanmon_cfgs(2);
5820         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5821         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5822         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5823         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::supported(), InitFeatures::supported());
5824         let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5825         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5826         nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5827         check_added_monitors!(nodes[0], 1);
5828         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5829         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).their_max_htlc_value_in_flight_msat + 1;
5830         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5831
5832         assert!(nodes[1].node.list_channels().is_empty());
5833         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
5834         assert_eq!(err_msg.data,"Remote HTLC add would put them over our max HTLC value");
5835         check_added_monitors!(nodes[1], 1);
5836 }
5837
5838 #[test]
5839 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
5840         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
5841         let chanmon_cfgs = create_chanmon_cfgs(2);
5842         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5843         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5844         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5845         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::supported(), InitFeatures::supported());
5846         let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 3999999, TEST_FINAL_CLTV).unwrap();
5847         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5848         nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5849         check_added_monitors!(nodes[0], 1);
5850         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5851         updates.update_add_htlcs[0].cltv_expiry = 500000000;
5852         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5853
5854         assert!(nodes[1].node.list_channels().is_empty());
5855         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
5856         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
5857         check_added_monitors!(nodes[1], 1);
5858 }
5859
5860 #[test]
5861 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
5862         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
5863         // We test this by first testing that that repeated HTLCs pass commitment signature checks
5864         // after disconnect and that non-sequential htlc_ids result in a channel failure.
5865         let chanmon_cfgs = create_chanmon_cfgs(2);
5866         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5867         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5868         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5869         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
5870         let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5871         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5872         nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5873         check_added_monitors!(nodes[0], 1);
5874         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5875         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5876
5877         //Disconnect and Reconnect
5878         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5879         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5880         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
5881         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
5882         assert_eq!(reestablish_1.len(), 1);
5883         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
5884         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
5885         assert_eq!(reestablish_2.len(), 1);
5886         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
5887         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
5888         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
5889         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
5890
5891         //Resend HTLC
5892         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5893         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
5894         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
5895         check_added_monitors!(nodes[1], 1);
5896         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5897
5898         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5899
5900         assert!(nodes[1].node.list_channels().is_empty());
5901         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
5902         assert_eq!(err_msg.data, "Remote skipped HTLC ID");
5903         check_added_monitors!(nodes[1], 1);
5904 }
5905
5906 #[test]
5907 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
5908         //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.
5909
5910         let chanmon_cfgs = create_chanmon_cfgs(2);
5911         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5912         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5913         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5914         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
5915
5916         let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5917         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5918         nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5919         check_added_monitors!(nodes[0], 1);
5920         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5921         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5922
5923         let update_msg = msgs::UpdateFulfillHTLC{
5924                 channel_id: chan.2,
5925                 htlc_id: 0,
5926                 payment_preimage: our_payment_preimage,
5927         };
5928
5929         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
5930
5931         assert!(nodes[0].node.list_channels().is_empty());
5932         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
5933         assert_eq!(err_msg.data, "Remote tried to fulfill/fail HTLC before it had been committed");
5934         check_added_monitors!(nodes[0], 1);
5935 }
5936
5937 #[test]
5938 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
5939         //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.
5940
5941         let chanmon_cfgs = create_chanmon_cfgs(2);
5942         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5943         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5944         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5945         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
5946
5947         let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5948         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5949         nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5950         check_added_monitors!(nodes[0], 1);
5951         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5952         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5953
5954         let update_msg = msgs::UpdateFailHTLC{
5955                 channel_id: chan.2,
5956                 htlc_id: 0,
5957                 reason: msgs::OnionErrorPacket { data: Vec::new()},
5958         };
5959
5960         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
5961
5962         assert!(nodes[0].node.list_channels().is_empty());
5963         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
5964         assert_eq!(err_msg.data, "Remote tried to fulfill/fail HTLC before it had been committed");
5965         check_added_monitors!(nodes[0], 1);
5966 }
5967
5968 #[test]
5969 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
5970         //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.
5971
5972         let chanmon_cfgs = create_chanmon_cfgs(2);
5973         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5974         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5975         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5976         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
5977
5978         let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5979         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5980         nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5981         check_added_monitors!(nodes[0], 1);
5982         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5983         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5984
5985         let update_msg = msgs::UpdateFailMalformedHTLC{
5986                 channel_id: chan.2,
5987                 htlc_id: 0,
5988                 sha256_of_onion: [1; 32],
5989                 failure_code: 0x8000,
5990         };
5991
5992         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
5993
5994         assert!(nodes[0].node.list_channels().is_empty());
5995         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
5996         assert_eq!(err_msg.data, "Remote tried to fulfill/fail HTLC before it had been committed");
5997         check_added_monitors!(nodes[0], 1);
5998 }
5999
6000 #[test]
6001 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6002         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6003
6004         let chanmon_cfgs = create_chanmon_cfgs(2);
6005         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6006         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6007         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6008         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
6009
6010         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6011
6012         nodes[1].node.claim_funds(our_payment_preimage, 100_000);
6013         check_added_monitors!(nodes[1], 1);
6014
6015         let events = nodes[1].node.get_and_clear_pending_msg_events();
6016         assert_eq!(events.len(), 1);
6017         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6018                 match events[0] {
6019                         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, .. } } => {
6020                                 assert!(update_add_htlcs.is_empty());
6021                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6022                                 assert!(update_fail_htlcs.is_empty());
6023                                 assert!(update_fail_malformed_htlcs.is_empty());
6024                                 assert!(update_fee.is_none());
6025                                 update_fulfill_htlcs[0].clone()
6026                         },
6027                         _ => panic!("Unexpected event"),
6028                 }
6029         };
6030
6031         update_fulfill_msg.htlc_id = 1;
6032
6033         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6034
6035         assert!(nodes[0].node.list_channels().is_empty());
6036         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6037         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6038         check_added_monitors!(nodes[0], 1);
6039 }
6040
6041 #[test]
6042 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6043         //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.
6044
6045         let chanmon_cfgs = create_chanmon_cfgs(2);
6046         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6047         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6048         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6049         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
6050
6051         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6052
6053         nodes[1].node.claim_funds(our_payment_preimage, 100_000);
6054         check_added_monitors!(nodes[1], 1);
6055
6056         let events = nodes[1].node.get_and_clear_pending_msg_events();
6057         assert_eq!(events.len(), 1);
6058         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6059                 match events[0] {
6060                         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, .. } } => {
6061                                 assert!(update_add_htlcs.is_empty());
6062                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6063                                 assert!(update_fail_htlcs.is_empty());
6064                                 assert!(update_fail_malformed_htlcs.is_empty());
6065                                 assert!(update_fee.is_none());
6066                                 update_fulfill_htlcs[0].clone()
6067                         },
6068                         _ => panic!("Unexpected event"),
6069                 }
6070         };
6071
6072         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6073
6074         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6075
6076         assert!(nodes[0].node.list_channels().is_empty());
6077         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6078         assert_eq!(err_msg.data, "Remote tried to fulfill HTLC with an incorrect preimage");
6079         check_added_monitors!(nodes[0], 1);
6080 }
6081
6082 #[test]
6083 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6084         //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.
6085
6086         let chanmon_cfgs = create_chanmon_cfgs(2);
6087         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6088         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6089         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6090         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::supported(), InitFeatures::supported());
6091         let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
6092         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6093         nodes[0].node.send_payment(route, our_payment_hash).unwrap();
6094         check_added_monitors!(nodes[0], 1);
6095
6096         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6097         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6098
6099         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6100         check_added_monitors!(nodes[1], 0);
6101         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6102
6103         let events = nodes[1].node.get_and_clear_pending_msg_events();
6104
6105         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6106                 match events[0] {
6107                         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, .. } } => {
6108                                 assert!(update_add_htlcs.is_empty());
6109                                 assert!(update_fulfill_htlcs.is_empty());
6110                                 assert!(update_fail_htlcs.is_empty());
6111                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6112                                 assert!(update_fee.is_none());
6113                                 update_fail_malformed_htlcs[0].clone()
6114                         },
6115                         _ => panic!("Unexpected event"),
6116                 }
6117         };
6118         update_msg.failure_code &= !0x8000;
6119         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6120
6121         assert!(nodes[0].node.list_channels().is_empty());
6122         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6123         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6124         check_added_monitors!(nodes[0], 1);
6125 }
6126
6127 #[test]
6128 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6129         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6130         //    * 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.
6131
6132         let chanmon_cfgs = create_chanmon_cfgs(3);
6133         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6134         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6135         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6136         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::supported(), InitFeatures::supported());
6137         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::supported(), InitFeatures::supported());
6138
6139         let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
6140         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6141
6142         //First hop
6143         let mut payment_event = {
6144                 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
6145                 check_added_monitors!(nodes[0], 1);
6146                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6147                 assert_eq!(events.len(), 1);
6148                 SendEvent::from_event(events.remove(0))
6149         };
6150         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6151         check_added_monitors!(nodes[1], 0);
6152         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6153         expect_pending_htlcs_forwardable!(nodes[1]);
6154         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6155         assert_eq!(events_2.len(), 1);
6156         check_added_monitors!(nodes[1], 1);
6157         payment_event = SendEvent::from_event(events_2.remove(0));
6158         assert_eq!(payment_event.msgs.len(), 1);
6159
6160         //Second Hop
6161         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6162         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6163         check_added_monitors!(nodes[2], 0);
6164         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6165
6166         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6167         assert_eq!(events_3.len(), 1);
6168         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6169                 match events_3[0] {
6170                         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 } } => {
6171                                 assert!(update_add_htlcs.is_empty());
6172                                 assert!(update_fulfill_htlcs.is_empty());
6173                                 assert!(update_fail_htlcs.is_empty());
6174                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6175                                 assert!(update_fee.is_none());
6176                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6177                         },
6178                         _ => panic!("Unexpected event"),
6179                 }
6180         };
6181
6182         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6183
6184         check_added_monitors!(nodes[1], 0);
6185         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6186         expect_pending_htlcs_forwardable!(nodes[1]);
6187         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6188         assert_eq!(events_4.len(), 1);
6189
6190         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6191         match events_4[0] {
6192                 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, .. } } => {
6193                         assert!(update_add_htlcs.is_empty());
6194                         assert!(update_fulfill_htlcs.is_empty());
6195                         assert_eq!(update_fail_htlcs.len(), 1);
6196                         assert!(update_fail_malformed_htlcs.is_empty());
6197                         assert!(update_fee.is_none());
6198                 },
6199                 _ => panic!("Unexpected event"),
6200         };
6201
6202         check_added_monitors!(nodes[1], 1);
6203 }
6204
6205 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6206         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6207         // 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
6208         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6209
6210         let chanmon_cfgs = create_chanmon_cfgs(2);
6211         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6212         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6213         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6214         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
6215
6216         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6217
6218         // We route 2 dust-HTLCs between A and B
6219         let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6220         let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6221         route_payment(&nodes[0], &[&nodes[1]], 1000000);
6222
6223         // Cache one local commitment tx as previous
6224         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6225
6226         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6227         assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2));
6228         check_added_monitors!(nodes[1], 0);
6229         expect_pending_htlcs_forwardable!(nodes[1]);
6230         check_added_monitors!(nodes[1], 1);
6231
6232         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6233         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6234         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6235         check_added_monitors!(nodes[0], 1);
6236
6237         // Cache one local commitment tx as lastest
6238         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6239
6240         let events = nodes[0].node.get_and_clear_pending_msg_events();
6241         match events[0] {
6242                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6243                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6244                 },
6245                 _ => panic!("Unexpected event"),
6246         }
6247         match events[1] {
6248                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6249                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6250                 },
6251                 _ => panic!("Unexpected event"),
6252         }
6253
6254         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6255         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6256         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6257
6258         if announce_latest {
6259                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_last_commitment_tx[0].clone()]}, 1);
6260         } else {
6261                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_prev_commitment_tx[0].clone()]}, 1);
6262         }
6263
6264         check_closed_broadcast!(nodes[0], false);
6265         check_added_monitors!(nodes[0], 1);
6266
6267         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6268         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 1, true,  header.bitcoin_hash());
6269         let events = nodes[0].node.get_and_clear_pending_events();
6270         // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
6271         assert_eq!(events.len(), 2);
6272         let mut first_failed = false;
6273         for event in events {
6274                 match event {
6275                         Event::PaymentFailed { payment_hash, .. } => {
6276                                 if payment_hash == payment_hash_1 {
6277                                         assert!(!first_failed);
6278                                         first_failed = true;
6279                                 } else {
6280                                         assert_eq!(payment_hash, payment_hash_2);
6281                                 }
6282                         }
6283                         _ => panic!("Unexpected event"),
6284                 }
6285         }
6286 }
6287
6288 #[test]
6289 fn test_failure_delay_dust_htlc_local_commitment() {
6290         do_test_failure_delay_dust_htlc_local_commitment(true);
6291         do_test_failure_delay_dust_htlc_local_commitment(false);
6292 }
6293
6294 #[test]
6295 fn test_no_failure_dust_htlc_local_commitment() {
6296         // Transaction filters for failing back dust htlc based on local commitment txn infos has been
6297         // prone to error, we test here that a dummy transaction don't fail them.
6298
6299         let chanmon_cfgs = create_chanmon_cfgs(2);
6300         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6301         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6302         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6303         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
6304
6305         // Rebalance a bit
6306         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
6307
6308         let as_dust_limit = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6309         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6310
6311         // We route 2 dust-HTLCs between A and B
6312         let (preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6313         let (preimage_2, _) = route_payment(&nodes[1], &[&nodes[0]], as_dust_limit*1000);
6314
6315         // Build a dummy invalid transaction trying to spend a commitment tx
6316         let input = TxIn {
6317                 previous_output: BitcoinOutPoint { txid: chan.3.txid(), vout: 0 },
6318                 script_sig: Script::new(),
6319                 sequence: 0,
6320                 witness: Vec::new(),
6321         };
6322
6323         let outp = TxOut {
6324                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
6325                 value: 10000,
6326         };
6327
6328         let dummy_tx = Transaction {
6329                 version: 2,
6330                 lock_time: 0,
6331                 input: vec![input],
6332                 output: vec![outp]
6333         };
6334
6335         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6336         nodes[0].chan_monitor.simple_monitor.block_connected(&header, 1, &[&dummy_tx], &[1;1]);
6337         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6338         assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
6339         // We broadcast a few more block to check everything is all right
6340         connect_blocks(&nodes[0].block_notifier, 20, 1, true,  header.bitcoin_hash());
6341         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6342         assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
6343
6344         claim_payment(&nodes[0], &vec!(&nodes[1])[..], preimage_1, bs_dust_limit*1000);
6345         claim_payment(&nodes[1], &vec!(&nodes[0])[..], preimage_2, as_dust_limit*1000);
6346 }
6347
6348 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6349         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6350         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6351         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6352         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6353         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6354         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6355
6356         let chanmon_cfgs = create_chanmon_cfgs(3);
6357         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6358         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6359         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6360         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
6361
6362         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6363
6364         let (_payment_preimage_1, dust_hash) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6365         let (_payment_preimage_2, non_dust_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6366
6367         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6368         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6369
6370         // We revoked bs_commitment_tx
6371         if revoked {
6372                 let (payment_preimage_3, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6373                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 1_000_000);
6374         }
6375
6376         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6377         let mut timeout_tx = Vec::new();
6378         if local {
6379                 // We fail dust-HTLC 1 by broadcast of local commitment tx
6380                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_commitment_tx[0].clone()]}, 1);
6381                 check_closed_broadcast!(nodes[0], false);
6382                 check_added_monitors!(nodes[0], 1);
6383                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6384                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6385                 let parent_hash  = connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 2, true, header.bitcoin_hash());
6386                 let events = nodes[0].node.get_and_clear_pending_events();
6387                 assert_eq!(events.len(), 1);
6388                 match events[0] {
6389                         Event::PaymentFailed { payment_hash, .. } => {
6390                                 assert_eq!(payment_hash, dust_hash);
6391                         },
6392                         _ => panic!("Unexpected event"),
6393                 }
6394                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6395                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6396                 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6397                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6398                 nodes[0].block_notifier.block_connected(&Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
6399                 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6400                 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 8, true, header_3.bitcoin_hash());
6401                 let events = nodes[0].node.get_and_clear_pending_events();
6402                 assert_eq!(events.len(), 1);
6403                 match events[0] {
6404                         Event::PaymentFailed { payment_hash, .. } => {
6405                                 assert_eq!(payment_hash, non_dust_hash);
6406                         },
6407                         _ => panic!("Unexpected event"),
6408                 }
6409         } else {
6410                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6411                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![bs_commitment_tx[0].clone()]}, 1);
6412                 check_closed_broadcast!(nodes[0], false);
6413                 check_added_monitors!(nodes[0], 1);
6414                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6415                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6416                 let parent_hash  = connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 2, true, header.bitcoin_hash());
6417                 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6418                 if !revoked {
6419                         let events = nodes[0].node.get_and_clear_pending_events();
6420                         assert_eq!(events.len(), 1);
6421                         match events[0] {
6422                                 Event::PaymentFailed { payment_hash, .. } => {
6423                                         assert_eq!(payment_hash, dust_hash);
6424                                 },
6425                                 _ => panic!("Unexpected event"),
6426                         }
6427                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6428                         // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
6429                         nodes[0].block_notifier.block_connected(&Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
6430                         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6431                         let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6432                         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 8, true, header_3.bitcoin_hash());
6433                         let events = nodes[0].node.get_and_clear_pending_events();
6434                         assert_eq!(events.len(), 1);
6435                         match events[0] {
6436                                 Event::PaymentFailed { payment_hash, .. } => {
6437                                         assert_eq!(payment_hash, non_dust_hash);
6438                                 },
6439                                 _ => panic!("Unexpected event"),
6440                         }
6441                 } else {
6442                         // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
6443                         // commitment tx
6444                         let events = nodes[0].node.get_and_clear_pending_events();
6445                         assert_eq!(events.len(), 2);
6446                         let first;
6447                         match events[0] {
6448                                 Event::PaymentFailed { payment_hash, .. } => {
6449                                         if payment_hash == dust_hash { first = true; }
6450                                         else { first = false; }
6451                                 },
6452                                 _ => panic!("Unexpected event"),
6453                         }
6454                         match events[1] {
6455                                 Event::PaymentFailed { payment_hash, .. } => {
6456                                         if first { assert_eq!(payment_hash, non_dust_hash); }
6457                                         else { assert_eq!(payment_hash, dust_hash); }
6458                                 },
6459                                 _ => panic!("Unexpected event"),
6460                         }
6461                 }
6462         }
6463 }
6464
6465 #[test]
6466 fn test_sweep_outbound_htlc_failure_update() {
6467         do_test_sweep_outbound_htlc_failure_update(false, true);
6468         do_test_sweep_outbound_htlc_failure_update(false, false);
6469         do_test_sweep_outbound_htlc_failure_update(true, false);
6470 }
6471
6472 #[test]
6473 fn test_upfront_shutdown_script() {
6474         // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
6475         // enforce it at shutdown message
6476
6477         let mut config = UserConfig::default();
6478         config.channel_options.announced_channel = true;
6479         config.peer_channel_config_limits.force_announced_channel_preference = false;
6480         config.channel_options.commit_upfront_shutdown_pubkey = false;
6481         let user_cfgs = [None, Some(config), None];
6482         let chanmon_cfgs = create_chanmon_cfgs(3);
6483         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6484         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
6485         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6486
6487         // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
6488         let flags = InitFeatures::supported();
6489         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
6490         nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6491         let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
6492         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6493         // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that  we disconnect peer
6494         nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
6495         assert_eq!(check_closed_broadcast!(nodes[2], true).unwrap().data, "Got shutdown request with a scriptpubkey which did not match their previous scriptpubkey");
6496         check_added_monitors!(nodes[2], 1);
6497
6498         // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
6499         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
6500         nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6501         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
6502         // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
6503         nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
6504         let events = nodes[2].node.get_and_clear_pending_msg_events();
6505         assert_eq!(events.len(), 1);
6506         match events[0] {
6507                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
6508                 _ => panic!("Unexpected event"),
6509         }
6510
6511         // We test that if case of peer non-signaling we don't enforce committed script at channel opening
6512         let mut flags_no = InitFeatures::supported();
6513         flags_no.unset_upfront_shutdown_script();
6514         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone());
6515         nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6516         let mut node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
6517         node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6518         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_1_shutdown);
6519         let events = nodes[1].node.get_and_clear_pending_msg_events();
6520         assert_eq!(events.len(), 1);
6521         match events[0] {
6522                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
6523                 _ => panic!("Unexpected event"),
6524         }
6525
6526         // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
6527         // channel smoothly, opt-out is from channel initiator here
6528         let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone());
6529         nodes[1].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6530         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
6531         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6532         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
6533         let events = nodes[0].node.get_and_clear_pending_msg_events();
6534         assert_eq!(events.len(), 1);
6535         match events[0] {
6536                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
6537                 _ => panic!("Unexpected event"),
6538         }
6539
6540         //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
6541         //// channel smoothly
6542         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone());
6543         nodes[1].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6544         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
6545         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6546         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
6547         let events = nodes[0].node.get_and_clear_pending_msg_events();
6548         assert_eq!(events.len(), 2);
6549         match events[0] {
6550                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
6551                 _ => panic!("Unexpected event"),
6552         }
6553         match events[1] {
6554                 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
6555                 _ => panic!("Unexpected event"),
6556         }
6557 }
6558
6559 #[test]
6560 fn test_user_configurable_csv_delay() {
6561         // We test our channel constructors yield errors when we pass them absurd csv delay
6562
6563         let mut low_our_to_self_config = UserConfig::default();
6564         low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
6565         let mut high_their_to_self_config = UserConfig::default();
6566         high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
6567         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
6568         let chanmon_cfgs = create_chanmon_cfgs(2);
6569         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6570         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
6571         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6572
6573         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
6574         let keys_manager: Arc<KeysInterface<ChanKeySigner = EnforcingChannelKeys>> = Arc::new(test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
6575         if let Err(error) = Channel::new_outbound(&&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &keys_manager, nodes[1].node.get_our_node_id(), 1000000, 1000000, 0, Arc::new(test_utils::TestLogger::new()), &low_our_to_self_config) {
6576                 match error {
6577                         APIError::APIMisuseError { err } => { assert_eq!(err, "Configured with an unreasonable our_to_self_delay putting user funds at risks"); },
6578                         _ => panic!("Unexpected event"),
6579                 }
6580         } else { assert!(false) }
6581
6582         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
6583         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6584         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6585         open_channel.to_self_delay = 200;
6586         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::supported(), &open_channel, 0, Arc::new(test_utils::TestLogger::new()), &low_our_to_self_config) {
6587                 match error {
6588                         ChannelError::Close(err) => { assert_eq!(err, "Configured with an unreasonable our_to_self_delay putting user funds at risks"); },
6589                         _ => panic!("Unexpected event"),
6590                 }
6591         } else { assert!(false); }
6592
6593         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
6594         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6595         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::supported(), &get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()));
6596         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6597         accept_channel.to_self_delay = 200;
6598         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::supported(), &accept_channel);
6599         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
6600                 match action {
6601                         &ErrorAction::SendErrorMessage { ref msg } => {
6602                                 assert_eq!(msg.data,"They wanted our payments to be delayed by a needlessly long period");
6603                         },
6604                         _ => { assert!(false); }
6605                 }
6606         } else { assert!(false); }
6607
6608         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
6609         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6610         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6611         open_channel.to_self_delay = 200;
6612         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::supported(), &open_channel, 0, Arc::new(test_utils::TestLogger::new()), &high_their_to_self_config) {
6613                 match error {
6614                         ChannelError::Close(err) => { assert_eq!(err, "They wanted our payments to be delayed by a needlessly long period"); },
6615                         _ => panic!("Unexpected event"),
6616                 }
6617         } else { assert!(false); }
6618 }
6619
6620 #[test]
6621 fn test_data_loss_protect() {
6622         // We want to be sure that :
6623         // * we don't broadcast our Local Commitment Tx in case of fallen behind
6624         // * we close channel in case of detecting other being fallen behind
6625         // * we are able to claim our own outputs thanks to remote my_current_per_commitment_point
6626         let keys_manager;
6627         let fee_estimator;
6628         let tx_broadcaster;
6629         let monitor;
6630         let node_state_0;
6631         let chanmon_cfgs = create_chanmon_cfgs(2);
6632         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6633         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6634         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6635
6636         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::supported(), InitFeatures::supported());
6637
6638         // Cache node A state before any channel update
6639         let previous_node_state = nodes[0].node.encode();
6640         let mut previous_chan_monitor_state = test_utils::TestVecWriter(Vec::new());
6641         nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut previous_chan_monitor_state).unwrap();
6642
6643         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
6644         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
6645
6646         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6647         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6648
6649         // Restore node A from previous state
6650         let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::with_id(format!("node {}", 0)));
6651         let mut chan_monitor = <(Sha256dHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut ::std::io::Cursor::new(previous_chan_monitor_state.0), Arc::clone(&logger)).unwrap().1;
6652         let chain_monitor = Arc::new(ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
6653         tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
6654         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
6655         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::clone(&logger));
6656         monitor = test_utils::TestChannelMonitor::new(chain_monitor.clone(), &tx_broadcaster, logger.clone(), &fee_estimator);
6657         node_state_0 = {
6658                 let mut channel_monitors = HashMap::new();
6659                 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chan_monitor);
6660                 <(Sha256dHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>)>::read(&mut ::std::io::Cursor::new(previous_node_state), ChannelManagerReadArgs {
6661                         keys_manager: &keys_manager,
6662                         fee_estimator: &fee_estimator,
6663                         monitor: &monitor,
6664                         logger: Arc::clone(&logger),
6665                         tx_broadcaster: &tx_broadcaster,
6666                         default_config: UserConfig::default(),
6667                         channel_monitors: &mut channel_monitors,
6668                 }).unwrap().1
6669         };
6670         nodes[0].node = &node_state_0;
6671         assert!(monitor.add_monitor(OutPoint { txid: chan.3.txid(), index: 0 }, chan_monitor).is_ok());
6672         nodes[0].chan_monitor = &monitor;
6673         nodes[0].chain_monitor = chain_monitor;
6674
6675         nodes[0].block_notifier = BlockNotifier::new(nodes[0].chain_monitor.clone());
6676         nodes[0].block_notifier.register_listener(&nodes[0].chan_monitor.simple_monitor);
6677         nodes[0].block_notifier.register_listener(nodes[0].node);
6678
6679         check_added_monitors!(nodes[0], 1);
6680
6681         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6682         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6683
6684         let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6685
6686         // Check we update monitor following learning of per_commitment_point from B
6687         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
6688         check_added_monitors!(nodes[0], 2);
6689
6690         {
6691                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
6692                 assert_eq!(node_txn.len(), 0);
6693         }
6694
6695         let mut reestablish_1 = Vec::with_capacity(1);
6696         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
6697                 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
6698                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
6699                         reestablish_1.push(msg.clone());
6700                 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
6701                 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
6702                         match action {
6703                                 &ErrorAction::SendErrorMessage { ref msg } => {
6704                                         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");
6705                                 },
6706                                 _ => panic!("Unexpected event!"),
6707                         }
6708                 } else {
6709                         panic!("Unexpected event")
6710                 }
6711         }
6712
6713         // Check we close channel detecting A is fallen-behind
6714         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6715         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
6716         check_added_monitors!(nodes[1], 1);
6717
6718
6719         // Check A is able to claim to_remote output
6720         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
6721         assert_eq!(node_txn.len(), 1);
6722         check_spends!(node_txn[0], chan.3);
6723         assert_eq!(node_txn[0].output.len(), 2);
6724         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6725         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()]}, 1);
6726         let spend_txn = check_spendable_outputs!(nodes[0], 1);
6727         assert_eq!(spend_txn.len(), 1);
6728         check_spends!(spend_txn[0], node_txn[0]);
6729 }
6730
6731 #[test]
6732 fn test_check_htlc_underpaying() {
6733         // Send payment through A -> B but A is maliciously
6734         // sending a probe payment (i.e less than expected value0
6735         // to B, B should refuse payment.
6736
6737         let chanmon_cfgs = create_chanmon_cfgs(2);
6738         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6739         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6740         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6741
6742         // Create some initial channels
6743         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
6744
6745         let (payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 10_000);
6746
6747         // Node 3 is expecting payment of 100_000 but receive 10_000,
6748         // fail htlc like we didn't know the preimage.
6749         nodes[1].node.claim_funds(payment_preimage, 100_000);
6750         nodes[1].node.process_pending_htlc_forwards();
6751
6752         let events = nodes[1].node.get_and_clear_pending_msg_events();
6753         assert_eq!(events.len(), 1);
6754         let (update_fail_htlc, commitment_signed) = match events[0] {
6755                 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 } } => {
6756                         assert!(update_add_htlcs.is_empty());
6757                         assert!(update_fulfill_htlcs.is_empty());
6758                         assert_eq!(update_fail_htlcs.len(), 1);
6759                         assert!(update_fail_malformed_htlcs.is_empty());
6760                         assert!(update_fee.is_none());
6761                         (update_fail_htlcs[0].clone(), commitment_signed)
6762                 },
6763                 _ => panic!("Unexpected event"),
6764         };
6765         check_added_monitors!(nodes[1], 1);
6766
6767         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
6768         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
6769
6770         let events = nodes[0].node.get_and_clear_pending_events();
6771         assert_eq!(events.len(), 1);
6772         if let &Event::PaymentFailed { payment_hash:_, ref rejected_by_dest, ref error_code } = &events[0] {
6773                 assert_eq!(*rejected_by_dest, true);
6774                 assert_eq!(error_code.unwrap(), 0x4000|15);
6775         } else {
6776                 panic!("Unexpected event");
6777         }
6778         nodes[1].node.get_and_clear_pending_events();
6779 }
6780
6781 #[test]
6782 fn test_announce_disable_channels() {
6783         // Create 2 channels between A and B. Disconnect B. Call timer_chan_freshness_every_min and check for generated
6784         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
6785
6786         let chanmon_cfgs = create_chanmon_cfgs(2);
6787         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6788         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6789         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6790
6791         let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported()).0.contents.short_channel_id;
6792         let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::supported(), InitFeatures::supported()).0.contents.short_channel_id;
6793         let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported()).0.contents.short_channel_id;
6794
6795         // Disconnect peers
6796         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6797         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6798
6799         nodes[0].node.timer_chan_freshness_every_min(); // dirty -> stagged
6800         nodes[0].node.timer_chan_freshness_every_min(); // staged -> fresh
6801         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
6802         assert_eq!(msg_events.len(), 3);
6803         for e in msg_events {
6804                 match e {
6805                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
6806                                 let short_id = msg.contents.short_channel_id;
6807                                 // Check generated channel_update match list in PendingChannelUpdate
6808                                 if short_id != short_id_1 && short_id != short_id_2 && short_id != short_id_3 {
6809                                         panic!("Generated ChannelUpdate for wrong chan!");
6810                                 }
6811                         },
6812                         _ => panic!("Unexpected event"),
6813                 }
6814         }
6815         // Reconnect peers
6816         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6817         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6818         assert_eq!(reestablish_1.len(), 3);
6819         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6820         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6821         assert_eq!(reestablish_2.len(), 3);
6822
6823         // Reestablish chan_1
6824         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6825         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6826         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6827         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6828         // Reestablish chan_2
6829         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
6830         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6831         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
6832         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6833         // Reestablish chan_3
6834         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
6835         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6836         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
6837         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6838
6839         nodes[0].node.timer_chan_freshness_every_min();
6840         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6841 }
6842
6843 #[test]
6844 fn test_bump_penalty_txn_on_revoked_commitment() {
6845         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
6846         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
6847
6848         let chanmon_cfgs = create_chanmon_cfgs(2);
6849         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6850         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6851         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6852
6853         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::supported(), InitFeatures::supported());
6854         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
6855         let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 3000000, 30).unwrap();
6856         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
6857
6858         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
6859         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
6860         assert_eq!(revoked_txn[0].output.len(), 4);
6861         assert_eq!(revoked_txn[0].input.len(), 1);
6862         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
6863         let revoked_txid = revoked_txn[0].txid();
6864
6865         let mut penalty_sum = 0;
6866         for outp in revoked_txn[0].output.iter() {
6867                 if outp.script_pubkey.is_v0_p2wsh() {
6868                         penalty_sum += outp.value;
6869                 }
6870         }
6871
6872         // Connect blocks to change height_timer range to see if we use right soonest_timelock
6873         let header_114 = connect_blocks(&nodes[1].block_notifier, 114, 0, false, Default::default());
6874
6875         // Actually revoke tx by claiming a HTLC
6876         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
6877         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6878         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_txn[0].clone()] }, 115);
6879         check_added_monitors!(nodes[1], 1);
6880
6881         // One or more justice tx should have been broadcast, check it
6882         let penalty_1;
6883         let feerate_1;
6884         {
6885                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6886                 assert_eq!(node_txn.len(), 3); // justice tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout (broadcasted from ChannelManager)
6887                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
6888                 assert_eq!(node_txn[0].output.len(), 1);
6889                 check_spends!(node_txn[0], revoked_txn[0]);
6890                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
6891                 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
6892                 penalty_1 = node_txn[0].txid();
6893                 node_txn.clear();
6894         };
6895
6896         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
6897         let header = connect_blocks(&nodes[1].block_notifier, 3, 115,  true, header.bitcoin_hash());
6898         let mut penalty_2 = penalty_1;
6899         let mut feerate_2 = 0;
6900         {
6901                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6902                 assert_eq!(node_txn.len(), 1);
6903                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
6904                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
6905                         assert_eq!(node_txn[0].output.len(), 1);
6906                         check_spends!(node_txn[0], revoked_txn[0]);
6907                         penalty_2 = node_txn[0].txid();
6908                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
6909                         assert_ne!(penalty_2, penalty_1);
6910                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
6911                         feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
6912                         // Verify 25% bump heuristic
6913                         assert!(feerate_2 * 100 >= feerate_1 * 125);
6914                         node_txn.clear();
6915                 }
6916         }
6917         assert_ne!(feerate_2, 0);
6918
6919         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
6920         connect_blocks(&nodes[1].block_notifier, 3, 118, true, header);
6921         let penalty_3;
6922         let mut feerate_3 = 0;
6923         {
6924                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6925                 assert_eq!(node_txn.len(), 1);
6926                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
6927                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
6928                         assert_eq!(node_txn[0].output.len(), 1);
6929                         check_spends!(node_txn[0], revoked_txn[0]);
6930                         penalty_3 = node_txn[0].txid();
6931                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
6932                         assert_ne!(penalty_3, penalty_2);
6933                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
6934                         feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
6935                         // Verify 25% bump heuristic
6936                         assert!(feerate_3 * 100 >= feerate_2 * 125);
6937                         node_txn.clear();
6938                 }
6939         }
6940         assert_ne!(feerate_3, 0);
6941
6942         nodes[1].node.get_and_clear_pending_events();
6943         nodes[1].node.get_and_clear_pending_msg_events();
6944 }
6945
6946 #[test]
6947 fn test_bump_penalty_txn_on_revoked_htlcs() {
6948         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
6949         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
6950
6951         let chanmon_cfgs = create_chanmon_cfgs(2);
6952         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6953         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6954         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6955
6956         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::supported(), InitFeatures::supported());
6957         // Lock HTLC in both directions
6958         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3_000_000).0;
6959         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
6960
6961         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
6962         assert_eq!(revoked_local_txn[0].input.len(), 1);
6963         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
6964
6965         // Revoke local commitment tx
6966         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
6967
6968         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6969         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
6970         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6971         check_closed_broadcast!(nodes[1], false);
6972         check_added_monitors!(nodes[1], 1);
6973
6974         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6975         assert_eq!(revoked_htlc_txn.len(), 6);
6976         if revoked_htlc_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
6977                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
6978                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
6979                 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
6980                 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6981                 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
6982         } else if revoked_htlc_txn[1].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
6983                 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
6984                 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
6985                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
6986                 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6987                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
6988         }
6989
6990         // Broadcast set of revoked txn on A
6991         let header_128 = connect_blocks(&nodes[0].block_notifier, 128, 0, true, header.bitcoin_hash());
6992         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6993         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);
6994         let first;
6995         let feerate_1;
6996         let penalty_txn;
6997         {
6998                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
6999                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7000                 // Verify claim tx are spending revoked HTLC txn
7001                 assert_eq!(node_txn[4].input.len(), 2);
7002                 assert_eq!(node_txn[4].output.len(), 1);
7003                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7004                 first = node_txn[4].txid();
7005                 // Store both feerates for later comparison
7006                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[4].output[0].value;
7007                 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7008                 penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7009                 node_txn.clear();
7010         }
7011
7012         // Connect three more block to see if bumped penalty are issued for HTLC txn
7013         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7014         nodes[0].block_notifier.block_connected(&Block { header: header_130, txdata: penalty_txn }, 130);
7015         {
7016                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7017                 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7018
7019                 check_spends!(node_txn[0], revoked_local_txn[0]);
7020                 check_spends!(node_txn[1], revoked_local_txn[0]);
7021
7022                 node_txn.clear();
7023         };
7024
7025         // Few more blocks to confirm penalty txn
7026         let header_135 = connect_blocks(&nodes[0].block_notifier, 5, 130, true, header_130.bitcoin_hash());
7027         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7028         let header_144 = connect_blocks(&nodes[0].block_notifier, 9, 135, true, header_135);
7029         let node_txn = {
7030                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7031                 assert_eq!(node_txn.len(), 1);
7032
7033                 assert_eq!(node_txn[0].input.len(), 2);
7034                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7035                 // Verify bumped tx is different and 25% bump heuristic
7036                 assert_ne!(first, node_txn[0].txid());
7037                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7038                 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7039                 assert!(feerate_2 * 100 > feerate_1 * 125);
7040                 let txn = vec![node_txn[0].clone()];
7041                 node_txn.clear();
7042                 txn
7043         };
7044         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7045         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7046         nodes[0].block_notifier.block_connected(&Block { header: header_145, txdata: node_txn }, 145);
7047         connect_blocks(&nodes[0].block_notifier, 20, 145, true, header_145.bitcoin_hash());
7048         {
7049                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7050                 // We verify than no new transaction has been broadcast because previously
7051                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7052                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7053                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7054                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7055                 // up bumped justice generation.
7056                 assert_eq!(node_txn.len(), 0);
7057                 node_txn.clear();
7058         }
7059         check_closed_broadcast!(nodes[0], false);
7060         check_added_monitors!(nodes[0], 1);
7061 }
7062
7063 #[test]
7064 fn test_bump_penalty_txn_on_remote_commitment() {
7065         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7066         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7067
7068         // Create 2 HTLCs
7069         // Provide preimage for one
7070         // Check aggregation
7071
7072         let chanmon_cfgs = create_chanmon_cfgs(2);
7073         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7074         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7075         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7076
7077         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::supported(), InitFeatures::supported());
7078         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7079         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7080
7081         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7082         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7083         assert_eq!(remote_txn[0].output.len(), 4);
7084         assert_eq!(remote_txn[0].input.len(), 1);
7085         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7086
7087         // Claim a HTLC without revocation (provide B monitor with preimage)
7088         nodes[1].node.claim_funds(payment_preimage, 3_000_000);
7089         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7090         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
7091         check_added_monitors!(nodes[1], 2);
7092
7093         // One or more claim tx should have been broadcast, check it
7094         let timeout;
7095         let preimage;
7096         let feerate_timeout;
7097         let feerate_preimage;
7098         {
7099                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7100                 assert_eq!(node_txn.len(), 5); // 2 * claim tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout + local HTLC-success (broadcasted from ChannelManager)
7101                 assert_eq!(node_txn[0].input.len(), 1);
7102                 assert_eq!(node_txn[1].input.len(), 1);
7103                 check_spends!(node_txn[0], remote_txn[0]);
7104                 check_spends!(node_txn[1], remote_txn[0]);
7105                 check_spends!(node_txn[2], chan.3);
7106                 check_spends!(node_txn[3], node_txn[2]);
7107                 check_spends!(node_txn[4], node_txn[2]);
7108                 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7109                         timeout = node_txn[0].txid();
7110                         let index = node_txn[0].input[0].previous_output.vout;
7111                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7112                         feerate_timeout = fee * 1000 / node_txn[0].get_weight() as u64;
7113
7114                         preimage = node_txn[1].txid();
7115                         let index = node_txn[1].input[0].previous_output.vout;
7116                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7117                         feerate_preimage = fee * 1000 / node_txn[1].get_weight() as u64;
7118                 } else {
7119                         timeout = node_txn[1].txid();
7120                         let index = node_txn[1].input[0].previous_output.vout;
7121                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7122                         feerate_timeout = fee * 1000 / node_txn[1].get_weight() as u64;
7123
7124                         preimage = node_txn[0].txid();
7125                         let index = node_txn[0].input[0].previous_output.vout;
7126                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7127                         feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7128                 }
7129                 node_txn.clear();
7130         };
7131         assert_ne!(feerate_timeout, 0);
7132         assert_ne!(feerate_preimage, 0);
7133
7134         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7135         connect_blocks(&nodes[1].block_notifier, 15, 1,  true, header.bitcoin_hash());
7136         {
7137                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7138                 assert_eq!(node_txn.len(), 2);
7139                 assert_eq!(node_txn[0].input.len(), 1);
7140                 assert_eq!(node_txn[1].input.len(), 1);
7141                 check_spends!(node_txn[0], remote_txn[0]);
7142                 check_spends!(node_txn[1], remote_txn[0]);
7143                 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7144                         let index = node_txn[0].input[0].previous_output.vout;
7145                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7146                         let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7147                         assert!(new_feerate * 100 > feerate_timeout * 125);
7148                         assert_ne!(timeout, node_txn[0].txid());
7149
7150                         let index = node_txn[1].input[0].previous_output.vout;
7151                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7152                         let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7153                         assert!(new_feerate * 100 > feerate_preimage * 125);
7154                         assert_ne!(preimage, node_txn[1].txid());
7155                 } else {
7156                         let index = node_txn[1].input[0].previous_output.vout;
7157                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7158                         let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7159                         assert!(new_feerate * 100 > feerate_timeout * 125);
7160                         assert_ne!(timeout, node_txn[1].txid());
7161
7162                         let index = node_txn[0].input[0].previous_output.vout;
7163                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7164                         let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7165                         assert!(new_feerate * 100 > feerate_preimage * 125);
7166                         assert_ne!(preimage, node_txn[0].txid());
7167                 }
7168                 node_txn.clear();
7169         }
7170
7171         nodes[1].node.get_and_clear_pending_events();
7172         nodes[1].node.get_and_clear_pending_msg_events();
7173 }
7174
7175 #[test]
7176 fn test_set_outpoints_partial_claiming() {
7177         // - remote party claim tx, new bump tx
7178         // - disconnect remote claiming tx, new bump
7179         // - disconnect tx, see no tx anymore
7180         let chanmon_cfgs = create_chanmon_cfgs(2);
7181         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7182         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7183         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7184
7185         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::supported(), InitFeatures::supported());
7186         let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7187         let payment_preimage_2 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7188
7189         // Remote commitment txn with 4 outputs: to_local, to_remote, 2 outgoing HTLC
7190         let remote_txn = get_local_commitment_txn!(nodes[1], chan.2);
7191         assert_eq!(remote_txn.len(), 3);
7192         assert_eq!(remote_txn[0].output.len(), 4);
7193         assert_eq!(remote_txn[0].input.len(), 1);
7194         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7195         check_spends!(remote_txn[1], remote_txn[0]);
7196         check_spends!(remote_txn[2], remote_txn[0]);
7197
7198         // Connect blocks on node A to advance height towards TEST_FINAL_CLTV
7199         let prev_header_100 = connect_blocks(&nodes[1].block_notifier, 100, 0, false, Default::default());
7200         // Provide node A with both preimage
7201         nodes[0].node.claim_funds(payment_preimage_1, 3_000_000);
7202         nodes[0].node.claim_funds(payment_preimage_2, 3_000_000);
7203         check_added_monitors!(nodes[0], 2);
7204         nodes[0].node.get_and_clear_pending_events();
7205         nodes[0].node.get_and_clear_pending_msg_events();
7206
7207         // Connect blocks on node A commitment transaction
7208         let header = BlockHeader { version: 0x20000000, prev_blockhash: prev_header_100, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7209         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 101);
7210         check_closed_broadcast!(nodes[0], false);
7211         check_added_monitors!(nodes[0], 1);
7212         // Verify node A broadcast tx claiming both HTLCs
7213         {
7214                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7215                 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-Success*2
7216                 assert_eq!(node_txn.len(), 4);
7217                 check_spends!(node_txn[0], remote_txn[0]);
7218                 check_spends!(node_txn[1], chan.3);
7219                 check_spends!(node_txn[2], node_txn[1]);
7220                 check_spends!(node_txn[3], node_txn[1]);
7221                 assert_eq!(node_txn[0].input.len(), 2);
7222                 node_txn.clear();
7223         }
7224
7225         // Connect blocks on node B
7226         connect_blocks(&nodes[1].block_notifier, 135, 0, false, Default::default());
7227         check_closed_broadcast!(nodes[1], false);
7228         check_added_monitors!(nodes[1], 1);
7229         // Verify node B broadcast 2 HTLC-timeout txn
7230         let partial_claim_tx = {
7231                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7232                 assert_eq!(node_txn.len(), 3);
7233                 check_spends!(node_txn[1], node_txn[0]);
7234                 check_spends!(node_txn[2], node_txn[0]);
7235                 assert_eq!(node_txn[1].input.len(), 1);
7236                 assert_eq!(node_txn[2].input.len(), 1);
7237                 node_txn[1].clone()
7238         };
7239
7240         // Broadcast partial claim on node A, should regenerate a claiming tx with HTLC dropped
7241         let header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7242         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![partial_claim_tx.clone()] }, 102);
7243         {
7244                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7245                 assert_eq!(node_txn.len(), 1);
7246                 check_spends!(node_txn[0], remote_txn[0]);
7247                 assert_eq!(node_txn[0].input.len(), 1); //dropped HTLC
7248                 node_txn.clear();
7249         }
7250         nodes[0].node.get_and_clear_pending_msg_events();
7251
7252         // Disconnect last block on node A, should regenerate a claiming tx with HTLC dropped
7253         nodes[0].block_notifier.block_disconnected(&header, 102);
7254         {
7255                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7256                 assert_eq!(node_txn.len(), 1);
7257                 check_spends!(node_txn[0], remote_txn[0]);
7258                 assert_eq!(node_txn[0].input.len(), 2); //resurrected HTLC
7259                 node_txn.clear();
7260         }
7261
7262         //// Disconnect one more block and then reconnect multiple no transaction should be generated
7263         nodes[0].block_notifier.block_disconnected(&header, 101);
7264         connect_blocks(&nodes[1].block_notifier, 15, 101, false, prev_header_100);
7265         {
7266                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7267                 assert_eq!(node_txn.len(), 0);
7268                 node_txn.clear();
7269         }
7270 }
7271
7272 #[test]
7273 fn test_counterparty_raa_skip_no_crash() {
7274         // Previously, if our counterparty sent two RAAs in a row without us having provided a
7275         // commitment transaction, we would have happily carried on and provided them the next
7276         // commitment transaction based on one RAA forward. This would probably eventually have led to
7277         // channel closure, but it would not have resulted in funds loss. Still, our
7278         // EnforcingChannelKeys would have paniced as it doesn't like jumps into the future. Here, we
7279         // check simply that the channel is closed in response to such an RAA, but don't check whether
7280         // we decide to punish our counterparty for revoking their funds (as we don't currently
7281         // implement that).
7282         let chanmon_cfgs = create_chanmon_cfgs(2);
7283         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7284         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7285         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7286         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported()).2;
7287
7288         let commitment_seed = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&channel_id).unwrap().local_keys.commitment_seed().clone();
7289         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7290         let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7291                 &SecretKey::from_slice(&chan_utils::build_commitment_secret(&commitment_seed, INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7292         let per_commitment_secret = chan_utils::build_commitment_secret(&commitment_seed, INITIAL_COMMITMENT_NUMBER);
7293
7294         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7295                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
7296         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7297         check_added_monitors!(nodes[1], 1);
7298 }
7299
7300 #[test]
7301 fn test_bump_txn_sanitize_tracking_maps() {
7302         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7303         // verify we clean then right after expiration of ANTI_REORG_DELAY.
7304
7305         let chanmon_cfgs = create_chanmon_cfgs(2);
7306         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7307         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7308         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7309
7310         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::supported(), InitFeatures::supported());
7311         // Lock HTLC in both directions
7312         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
7313         route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
7314
7315         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7316         assert_eq!(revoked_local_txn[0].input.len(), 1);
7317         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7318
7319         // Revoke local commitment tx
7320         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 9_000_000);
7321
7322         // Broadcast set of revoked txn on A
7323         let header_128 = connect_blocks(&nodes[0].block_notifier, 128, 0,  false, Default::default());
7324         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7325         nodes[0].block_notifier.block_connected(&Block { header: header_129, txdata: vec![revoked_local_txn[0].clone()] }, 129);
7326         check_closed_broadcast!(nodes[0], false);
7327         check_added_monitors!(nodes[0], 1);
7328         let penalty_txn = {
7329                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7330                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
7331                 check_spends!(node_txn[0], revoked_local_txn[0]);
7332                 check_spends!(node_txn[1], revoked_local_txn[0]);
7333                 check_spends!(node_txn[2], revoked_local_txn[0]);
7334                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7335                 node_txn.clear();
7336                 penalty_txn
7337         };
7338         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7339         nodes[0].block_notifier.block_connected(&Block { header: header_130, txdata: penalty_txn }, 130);
7340         connect_blocks(&nodes[0].block_notifier, 5, 130,  false, header_130.bitcoin_hash());
7341         {
7342                 let monitors = nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap();
7343                 if let Some(monitor) = monitors.get(&OutPoint::new(chan.3.txid(), 0)) {
7344                         assert!(monitor.onchain_tx_handler.pending_claim_requests.is_empty());
7345                         assert!(monitor.onchain_tx_handler.claimable_outpoints.is_empty());
7346                 }
7347         }
7348 }
7349
7350 #[test]
7351 fn test_override_channel_config() {
7352         let chanmon_cfgs = create_chanmon_cfgs(2);
7353         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7354         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7355         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7356
7357         // Node0 initiates a channel to node1 using the override config.
7358         let mut override_config = UserConfig::default();
7359         override_config.own_channel_config.our_to_self_delay = 200;
7360
7361         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7362
7363         // Assert the channel created by node0 is using the override config.
7364         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7365         assert_eq!(res.channel_flags, 0);
7366         assert_eq!(res.to_self_delay, 200);
7367 }
7368
7369 #[test]
7370 fn test_override_0msat_htlc_minimum() {
7371         let mut zero_config = UserConfig::default();
7372         zero_config.own_channel_config.our_htlc_minimum_msat = 0;
7373         let chanmon_cfgs = create_chanmon_cfgs(2);
7374         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7375         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7376         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7377
7378         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7379         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7380         assert_eq!(res.htlc_minimum_msat, 1);
7381
7382         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::supported(), &res);
7383         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7384         assert_eq!(res.htlc_minimum_msat, 1);
7385 }